1

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!

Trey Copeland
  • 3,387
  • 7
  • 29
  • 46

2 Answers2

0

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/

Community
  • 1
  • 1
RPichioli
  • 3,245
  • 2
  • 25
  • 29
0

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.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • This does not work. Your example allows both www & non-www to resolve 200 – Trey Copeland Oct 03 '16 at 22:14
  • No, first rule will redirect all non-www URLs to www URLs. You must clear browser cache and make sure both www and non-www are pointing to this htaccess – anubhava Oct 03 '16 at 23:12