Redirecting URLs with mod_rewrite

Posted May 12th, 2010 in Bread-crumbs and tagged by admin

If you’ve ever needed to move a web page’s location or change it’s URL but didn’t want to break external links to it as well as loose your Google juice, you can use Apache’s mod_rewrite to redirect a user’s browser automatically to the new location. Although there are many ways to do this with simple URL names it can become more challenging when using dynamic links. The question mark is a special character and escaping it doesn’t produce the desired effect when used on URLs like somepage.php?id=12&yada=yada.

When I changed my URLs to pretty human readable URLs I used the following to keep from breaking my links.



So in my httpd.conf I added the following stanza that redirects the old URL to the new URL.

RewriteEngine  on
RewriteCond %{QUERY_STRING} ^pid=29$
RewriteRule .* /technical/how-to-install-postfix-dovecot-amavis-clamav-and-spamassassin-etch/? [R=301,L]

One word of caution. Don’t forget to add the question mark at the end of the new URL as this forces a blank query string. Otherwise, the original query string will be retained and appended to the end of the URL producing a 404 page.

Comments are closed.