So much of Apache’s mod_rewrite is a mystery to me that I wonder if I’ll ever be able to write anything but the most basic ruleset without multiple trials and errors. Today, though, I stumbled upon a nice bit of information in Apache Cookbook by Ken Coar and Rich Bowen that I’m sure will come in handy next time I start hacking away in the .htaccess file.
The authors present this snippet for giving users their own web space on a server:
ReWriteEngine On RewriteCond "/home/$1/public_html" RewriteRule "/([^/]+)/(.*)" "home/$1/public_html/$2"
While I doubt I’ll ever need to use that exact ruleset, this paragraph in the “Discussion” section — especially the part that I mark in bold — has helped, more than anything else I’ve read, to reduce my bewilderment over mod_rewrite:
This rewrite ruleset takes advantage of a little-known fact about mod_rewrite — in particular, that a RewriteRule is always considered first, and, if it matches, the RewriteCond is evaluated after that. Consequently, we can use
$1in the RewriteCond , even though the value of that variable is set in the RewriteRule appearing on the following line.
Note to self
Commit this to memory: The RewriteRule is always considered first!