Saturday, April 30, 2011

Using .htaccess to Redirect Renamed or Deleted Web Pages, Forums, and Directories

A web admin may have a good reason for renaming the stray page or directory on a web site, but doing so impacts search engine optimization. One wouldn't wish to greet visitors or search engines accessing old links with a clumsy 404 page. An elegant solution is to redirect access attempts to a new page. For a simple rename, this is easy enough:
redirect 301 /Atheism.html /atheism.html
Any hits on Atheism.html will be redirected to atheism.html. This is clear, economical code, the best choice for a simple scenario like that. But what about the case of deleted forums with variable links, such as /messages/techforum/posts/, followed by many links such as 2009/12/75433.html? A common desire is to redirect many links in a directory to a single directory or file. The 301 technique no longer serves in that scenario.

My solution is to use Apache's RewriteCond command, which requires the following line somewhere near the beginning of your .htaccess file:
RewriteEngine on
With that prerequisite in place, one can then use RewriteCond and RewriteRule to redirect requests for /messages/techforum/post/2009/12/75433.html, for instance, to notice.html:
RewriteCond %{REQUEST_URI} /messages/
RewriteRule ^(.*)$ /notice.html [R=301,L]
REQUEST_URI is an environmental variable with the specific page accessed on the web site, excluding the web site's base url. The RewriteRule drops all text after the base url and replaces it with notice.html, which then should appear on the user's browser.

No comments:

techlorebyigor is my personal journal for ideas & opinions