Using mod_rewrite (RewriteRule) in .htaccess file on Apache
I’ve been tearing my hair out recently over a problem using mod_rewrite in the .htaccess file in Apache.
The mod_rewrite module provides a means of manipulating the URL and giving a different page to the one originally requested. A common use is being able to take a complicated URL and give an alternative easier url that users can use. For example you could have a complicated url such as /directory/script.php?page=234 and have a more user friendly url such as /rewriteinfo.
There are other ways of performing basic URL redirection using mod_alias and the Redirect or RedirectMatch rules, but these don’t work on query strings (i.e. the part of the url after the question mark ‘?’).
I’ve used mod_rewrite quite a bit in the past and have written a short guide: Basic guide to Apache mod_rewrite
It was therefore very frustrating when I created some RewriteRules on my hosted web site and couldn’t get them to work. The difference was that I didn’t have access to edit the configuration files directly, but I did have the ability to add the rules to a .htaccess file. The .htaccess file is a way of allowing users of the system (webmasters) to be able to enter a limited set of configuration options without having write access to the system configuration files (actually it’s a bit more than that, but that is the reason that it’s used in this example).
The rule that I added was on my First Aid Quiz web site. The idea was to remap the easy url www.firstaidquiz.com/firstaidmanual, to a blog entry, which included a query string. The reason I created this using mod_rewrite is that I will be wanting to change it to point to a new entry in future, when I’ve had opportunity to perform a proper review of the manual.
The rule I added (which worked when on my own server in the virtual hosts configuration file), was:
RewriteEngine on RewriteRule ^/firstaidmanual$ http://www.firstaidquiz.com/viewnews.php?blog=248 [L]
I was frustrated this this didn’t appear to be matched. After a lot of playing around with the format it turns out the problem was the initial forward slash ‘/’ on the regular expression. The working code is therefore:
RewriteEngine on RewriteRule ^firstaidmanual$ http://www.firstaidquiz.com/viewnews.php?blog=248 [L]
I expect that this is because the .htaccess is in the top directory and is therefore being applied relative to that. This is a bit unusual as the Redirect and RedirectMatch entries used by mod_alias work the other way (in that you do need the initial /).