Rewriting Dynamic Urls

There are a lot of good resources out there for rewriting urls, but most seem to only give you half the information you need. They’ll give you enough to rewrite the url, but then when you need to setup an external redirect for that page, they are strangely quiet. Say you have a page that is currently

http://www.example.com/products/product?pid=28

and you think it’d be better for the search engines if it was

http://www.example.com/products/green-widgets.html

So we need to internally rewrite “products/product?pid=28″ to “green-widgets.html” and then externally redirect “products/product?pid=28″ to “green-widgets.html”. This example is further complicated by the presence of a query string in the url to be redirected, but fear not, using this code will bring the desired results:

# Enable mod_rewrite, start rewrite engine
Options +FollowSymLinks
RewriteEngine on
#
# Internally rewrite search engine friendly static URL to dynamic filepath and query
RewriteRule ^green-widgets.html$ /product/product.php?pid=28 [L]

# Externally redirect client requests for old dynamic URLs to equivalent new static URLs
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /product/product\.php\?pid=28\ HTTP/
RewriteCond %{QUERY_STRING} ^pid=28$
RewriteRule ^product/product.php$ http://www.example.com/green-widgets.html? [R=301,L]

Of course, there may be those who think you don’t need to rewrite your dynamic urls anymore, but I’d rather rank for green widgets than product?pid=28, how about you? ;-)

No Comments »

admin on April 13th 2009 in Tips & Tricks, Url Rewriting

Trackback URI | Comments RSS

Leave a Reply