Forum Moderators: phranque
I am trying to build SEO Friendly URLs from this:
http://www.example.com/detail.php?id=1
to this:
http://www.example.com/product-category/productname/
We only have a handful of products, so I will have to create a rule for each as well as redirect the old URLs to the new ones.
Here is what I have tried so far:
#Internally rewrite SEO-friendly URL
RewriteRule ^product-category/productname/$ detail.php?id=1 [NC,L]
# Externally redirect requests back to SEO-friendly URL
RewriteCond %{QUERY_STRING} ^id=1$
RewriteRule ^detail\.php$ http://www.example.com/product-category/productname/? [R=301,L]
The rewrite works fine, but when I try the redirect... it keeps looping.
I have searched all over trying several solutions, but I can't seem to figure it out.
Thanks in advance for any suggestions!
Because your two rules countermand each other, the predictable result is a loop. You need to check that the 'unfriendly' URL is being requested by a client, rather than as the result of the previously-executed internal rewrite:
# Externally redirect only direct client requests for unfriendly URL back to SEO-friendly URL
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /detail\.php\?id=1\ HTTP/
RewriteRule ^detail\.php$ http://www.example.com/product-category/productname/? [R=301,L]
GET detail.php?id=1 HTTP/1.1
Jim
Since mod_rewrite (or mod_alias) has no way to know that id=1 is a large fuzzy green widget and id=2 is a small smooth blue widget, redirecting old to new URLs using mod_rewrite or mod_alias can be really inefficient and painful. So it's better to keep the symmetry between the friendly URL and the script variables in mod_rewrite, and use the database to associate product names with id numbers.
If this isn't clear, go change the id number on one of your products, and work though all the required changes and redirects with that as an example. Now do it several dozen times... Compare that with what happens if you keep the product name in the script query: You can handle all possible future product replacement redirects in your script with a few lines of code, and simply edit your database when a product changes or goes obsolete. A few lines of script code and a "replaced by/redirect to" field in your database are all that is required, instead of having to add a new redirect rule to your .htaccess file every time a product changes.
Jim