views:

137

answers:

1

Hey there,

Haven't been able to find a solution to this around the net or these forums - apologise if I've missed something!

My .htaccess RewriteRules are working well - have search-engine and user -friendly links in my web pages, and unfriendly database URLs running hidden in the background.

Except when I added a RewriteRule to add "www." to the front of URLs if the user didn't enter it - to ensure only one appears in search engines. Here's what now happening, and I can't figure out why!

My friendly URL structure for content is like this, and the database query string uses the first "importantword":

www.example.com/importantword-nonimportantword/

.htaccess snippet:

Options +FollowSymLinks
Options -Indexes

RewriteEngine on
RewriteOptions MaxRedirects=10

RewriteBase /

RewriteRule ^/$ index.php [L]

RewriteRule ^(.*)-(.*)/overview/$ detail.php?categoryID=$1 [L]

RewriteCond %{HTTP_HOST} !^www.example.com$
RewriteRule ^(.*)$ http://www.example.com/$1 [L]

What's happening since I added the last 2 lines:

CASE 1: user types (or clicks) www.example.com/honda-vehicle/overview/
- Works correctly
- They are taken to the correct page and the browser URL bar says:

www.example.com/honda-vehicles/overview/

CASE 2: user types example.com
- Works correctly
- They are taken to www.example.com and the browser URL bar says:

www.example.com

CASE 3: user types (or clicks) example.com/honda-vehicles/overview/ i.e. without the prefix "www"
- Does NOT work correctly
- They are taken to the right page, but the browser URL bar displays the unfriendly URL:

www.example.com/detail.php?categoryID=honda 

I figure there's some issue with the order of the RewriteRules, but it's doing my head in trying to logically step through it and figure it out!

Any assistance at all or pointers would be most appreciated!

A: 

Rules are applied in the order they appear. That means, when honda-vehicles/overview/ is requested, your second rule is applied, rewriting the path to detail.php?categoryID=honda. And due to the L flag, the current rewrite process is stopped immediately but also restarted with the new URL, causing that now the third rule is applied.

You can fix this by simply changing the order. Put your last rule as first rule (and add the R flag):

RewriteCond %{HTTP_HOST} !^www.example.com$
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

The rule of thumb is to put those rules, that cause an external redirect, in front of those rules, that just cause an internal rewrite.

Gumbo
Thanks for the insight! Your suggestion works perfectly and the explanation makes sense. Much much appreciated!
axol