skip to Main Content

I have a website where i do blogging… on my blog.php page i have posts from different categories.
when a user clicks on a link it is being redirect to /blog-details.php page with $_GET['title'] variable.

what I have tried

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f

#remove .php from all pages
RewriteRule ^([^.]+)$ $1.php [NC]

#blog/title-here
RewriteRule ^blog/([A-Za-z0-9-+]+)/?$ /blog-details.php?title=$1 [NC,L,QSA]

last line gives me something like

xyz.com/blog-details?title=hello-world

what i want to achieve is

xyz.com/blog/hello-world

not like

xyz.com/blog-details?title=hello-world

thank you, looking forward to answers.

2

Answers


  1. An important thing you have to take into consideration when working with .htaccess files, is that you have to check if the path is a directory or file, then proceed to do your action.

    I used your code and it worked properly, but simply added the -f and -d checks to make sure that this does not affect other pages.

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    
    #remove .php from all pages
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^.]+)$ $1.php [NC]
    
    #blog/title-here
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^blog/([A-Za-z0-9-+]+)/?$ /blog-details.php?title=$1 [NC,L,QSA]
    

    To test out your .htaccess file and with some dummy URLs, I’d highly recommend you to check out MadeWithLove

    https://htaccess.madewithlove.be/

    This will let you have a test input URL and see if you get the proper output URL (the actual URL your server would read).


    With that being said, I would recommend you to look into routing for future projects and self-development. A framework I’d recommend checking out is fat-free framework (f3) for PHP. It’s very easy to get into, you could learn it in 2 days, and it saves a lot of time in development – by containing routing, ORM, global variables, simplified SQL queries, and plenty of other features that essentially keep you a PHP developer, rather than a framework developer.

    Login or Signup to reply.
  2. use below method:

    <IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule ^blog/([0-9a-zA-Z_=-]+)$ blog-details.php?title=$1 [NC]
    </IfModule>
    

    Then you can access the title like $_GET[‘title’] on the page.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search