skip to Main Content

My current .htaccess looks like this:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301]
RewriteRule /([^/.]+)/?$ /restaurants.php?id=$1 [L,NC,QSA]
RewriteCond %{THE_REQUEST} ^.*/index.php 
RewriteRule ^(.*)index.php$ /$1 [R=301,L] 

I want my urls to be SEO friendly, which I figured out how to rewrite example.com/restaurants.php?id=123 to www.example.com/name/123.

The issue is when you go to non-www example.com/name/123, it redirects to the ugly url example.com/restaurants.php?id=123, which then redirects back to the SEO friendly clean www.example.com/name/123

How can I fix the non-www version to work?

Thanks for your time!

2

Answers


  1. Talking about the “www” you can see something here:
    .htaccess Remove WWW from URL + Directories

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^www.(.*)$ [NC]
    RewriteRule ^(.*)$ http://%1%{REQUEST_URI} [R=301,QSA,NC,L]
    

    To the URL, you can do something like:

    RewriteRule  ^some_alias/([0-9]+)/?$  real_page_name.php?id=$1
    

    In your case (you’ve used “name” in place of “restaurants.php”), simply:

    RewriteRule  ^name/([0-9]+)/?$  restaurants.php?id=$1
    

    Here you can get a lot of explanations and examples:
    https://www.addedbytes.com/articles/for-beginners/url-rewriting-for-beginners/

    Login or Signup to reply.
  2. Have your rules in this order:

    RewriteEngine On
    
    RewriteCond %{HTTP_HOST} ^example.com$ [NC]
    RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
    
    RewriteCond %{THE_REQUEST} ^.*/index.php 
    RewriteRule ^(.*)index.php$ /$1 [R=301,L,NE] 
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule /([^/.]+)/?$ /restaurants.php?id=$1 [L,NC,QSA]
    

    Make sure to clear your browser cache whiel testing this.

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