The Apache mod_rewrite module is a very powerful feature of Apache that is sometimes overlooked. For example, I needed to change all requests for http://computerglitch.net
to http://www.computerglitch.net
to do this I added the following code to the vhost file for computerglitch.net:
1 2 3 |
|
Lets go over step by step what this code is actually doing.
Line 1
turns the runtime rewriting engine on or off. This line needs to be on in the vhosts file in order for the configuration to work because rewrite configurations are not inherited by virtual hosts.
Line 2
condition matches if the Host portion of the HTTP request header begins with computerglitch.net
Line 3
rewrite computerglitch.net as http://www.computerglitch.net, reply with a 301 Moved Permanently response and stop any later rules from affecting this url.
A little more detail about the regular expression used on Line 3
1
|
|
^
begins the line to match
()
designates the portion to preserve for use again in the $1
variable.
.
matches any non-whitespace character
*
means the previous character can be matched zero or more times
$
ends the line to match
To explain this with a couple of examples:
^keyboard$
matches keyboard exactly^keyboard.*$
matches keyboard2000, keyboard2001, etc.^.*$
matches everything
For more information on perl regular expressions see: http://perldoc.perl.org/perlre.html#Regular-Expressions
Breaking this down you can see how it works with the following HTTP Request Header, HTTP Response Header and Response Body:
HTTP Request Header
1 2 3 4 5 6 7 8 |
|
HTTP Response Header
1 2 3 4 5 |
|
Response Body
1 2 3 4 5 6 7 8 9 |
|