mod_rewrite Saves the Day
permalinkI wanted to move all of my old articles into yearly subdirectories, but I didn’t want to break any of the incoming links to my site. Thankfully, mod_rewrite allows me to redirect incoming requests as necessary!
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} ^(.*/news)/
RewriteCond %1/2004/$1 -f
RewriteRule ^news/([^/]+)$ /news/2004/$1 [R,L]
RewriteCond %{REQUEST_FILENAME} ^(.*/news)/
RewriteCond %1/2003/$1 -f
RewriteRule ^news/([^/]+)$ /news/2003/$1 [R,L]
RewriteRule ^(.+) - [PT]
Basically, these rules check to see if the file exists in the /news/2004/
or /news/2003
subdirectories and, if so, redirects immediately to the yearly subdirectory.
It took me a while to figure out how to do this, but I think I’ve got a good idea of what’s going on.
The strange (but cool?) thing about mod_rewrite is that you can use the “back-references” captured in the RewriteRule
in the RewriteCond
lines! In the rules above, %1
represents the request filename captured in the first RewriteCond
, while $1
represents the URI segment captured in the RewriteRule below. See figure 1 in the mod_rewrite manual page for more information on how this works.
If you want to figure this stuff out for your own nefarious purposes, here are some links to help:
- http://www.modrewrite.com/: A gateway to a number of different sites
- Apache mod_rewrite module manual page: The official reference, complete but lacks some detail and examples
- A Users Guide to URL Rewriting with the Apache Webserver: The best example reference there is