Adventures with Apache's mod_rewrite

Album Cover: Life After Death

"While your gun's raisin', mine is blazin'."
The Notorious B.I.G. / I Love the Dough

Posted on April 16, 2004 12:28 AM in Web Development
Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.

Once again I found myself working on something that apparently no one has ever tried in the past. Since last night I have been reading through document after document online trying to figure out how to do some simple website redirection using Apache's mod_rewrite module.

I've come to the conclusion that either no one has ever had a need for accomplishing what I needed to accomplish, or they were all mod_rewrite geniuses and didn't leave any kind of a bit trail (like that?) behind them. Either way, I was left to my own devices to try and figure out how to get any requests to and all documents below to forward to the domain. I ended up placing .htaccess files in several directories and swapping out many different variations of domain name-matching regular expressions before I found a solution that did the job:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^ [NC]
RewriteRule ^bernie/(.+)$1 [R=301,L]

Essentially, the first line turns the RewriteEngine on (obviously); the second line checks for requests to the domain (the NC allows for case-insensitivity); and the third line tells the server to return a 301 status code before redirecting to the same path (without the /bernie subdirectory) on domain.

Now of course, being the troublemaker that I am, once I had finally gotten things working I wanted to do more. I noticed that a Google search on my name returned an outdated reference to /bernie/design.html on the domain. This has long since been changed to my web design page at design.php. So, my .htaccess file ends up looking like:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^ [NC]
RewriteRule ^bernie/(.+)$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule design.html$ /design.php [R=301,L]

In this set of conditions and rules, the fourth line denotes that the upcoming rule is only to be imposed on requests to the domain. The fifth line denotes that the upcoming rule should only be applied in the case that the requested filename isn't found on the server. The final line, which is comprised of the rule, denotes that in the case of the requested, failing file matching design.html, the request should be marked as permanently moved and then redirected to design.php at the root of the domain.


No one has added any comments.

Post Comments

If you feel like commenting on the above item, use the form below. Your email address will be used for personal contact reasons only, and will not be shown on this website.


Email Address:



Check this box if you hate spam.