All Hail mod_rewrite
I’m sure that I’m late to the party on this, but I just had to mention how awesome mod_rewrite is. If you haven’t heard of it, mod_rewrite is an Apache server module that uses a rule-based rewriting engine to rewrite requested URLs on the fly.
As you may know, I moved some things around during my redesign. I had a lot of pages that I wanted to redirect to new URLs. I also had a few pages that I removed completely, so I wanted to send the appropriate headers to the browser to indicate that they were removed. mod_rewrite handled both of these situations nicely. It took some reading and some help from the kind folks at WebmasterWorld, but I eventually figured it out.
Here’s an example of how mod_rewrite works:
The page located here:
http://unraveled.com/joshua/archives/2002/12/user_agent_accessibility_guidelines.shtml
was one of the many pages that I wanted to redirect. This specific page’s new home is here:
http://unraveled.com/archives/2002/12/user_agent_accessibility_guidelines.shtml
While I was figuring out how to use mod_rewrite, I used a JavaScript redirect, which worked well, but it wasn’t as smooth as I wanted it to be. I added the following two lines to my .htaccess file and my problem was solved.
RewriteEngine on
RewriteRule ^joshua/archives/([0-9]+)/([0-9]+)/([^\.]+)\.shtml$ /archives/$1/$2/$3.shtml [R=301,L]
The first line enables the rewrite engine. The second line says, “When the browser requests a page with the pattern, ‘/joshua/archives/(any number)/(any number)/(any file name).shtml,’ redirect the browser to, ‘/archives/(the first number above)/(the second number above)/(the file name above).shtml.’ Also, send a redirect flag with the code that means ‘Moved Permanently.’ Finally, stop the rewriting process here. To see mod_rewrite in action, just go to one of my old URLs.
If you want to learn more about mod_rewrite, I recommend the Apache documentation on the topic, A Tao of Regular Expressions and this thread at WebmasterWorld.
- 30 May 03
- programming, unraveled, web design
Go back to the top of this entry ↑

Comments