In the post “Mod_rewrite, how could I forget?!?” I wrote about using an htaccess generated by ColdFusion to make links that will display as blah.com/product rather than blah.com/index.cfm?page=123. In practice, as usual, it was a bit more tricky than most mod_rewrite tutorials put it–not vastly different, but just enough to require about 1/2 hour of research.
The revelation was found in the Apache documentation (as it should be). There was a boxed off note describing the operation of RewriteRule directives in htaccess files. Then there was a listing of the effects of different RewriteRules. Using the two, I figured out the problem…
In the aforementioned post, I asserted that in an htaccess file you could write
RewriteRule ^/search/(.*) /search.php?query=$1
But this is not true! Apache strips the path up to the current directory including the / from the URL before passing it through an htaccess RewriteRule. Thus, if you put the htaccess file in / (relative to the the site document root), accessing /products/toilet would pass the string products/toilet into the RewriteRules. If the htaccess file was in the /products directory, the same request would pass only toilet into the RewriteRules. Thus, to make the above rule work, it would have to look like this:
RewriteRule ^search/(.*) search.php?query=$1
As you can see, not a significant change, but the subtle difference will make or break it. Now an example of a RewriteRule in an htaccess folder in a subdirectory. Let’s say there’s a file named /products/main/search.php. If the htaccess file is in /products, the following rule could be made
RewriteRule ^search/(.*) main/search.php?query=$1
and then /products/search/shoes would display the result of /products/main/search.php?query=shoes, but retain the original URL in the browser.