Computerglitch

An ongoing adventure

Apache Mod_rewrite

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
RewriteEngine On
    RewriteCond %{HTTP_HOST} ^computerglitch\.net
    RewriteRule ^(.*)$ http://www.computerglitch.net/$1 [R=permanent,L]

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
    GET / HTTP/1.1[CRLF]
    Host: computerglitch.net[CRLF]
    Connection: close[CRLF]
    User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9) Gecko/2008052906 Firefox/3.0[CRLF]
    Accept-Encoding: gzip[CRLF]
    Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7[CRLF]
    Cache-Control: no-cache[CRLF]
    Accept-Language: de,en;q=0.7,en-us;q=0.3[CRLF]

HTTP Response Header

1
2
3
4
5
Server: Apache
Location: http://www.computerglitch.net/
Content-Length: 322
Connection: close
Content-Type: text/html; charset=iso-8859-1

Response Body

1
2
3
4
5
6
7
8
9
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="http://www.computerglitch.net/">here</a>.</p>
<hr>
<address>Apache Server at computerglitch.net Port 80</address>
</body></html>

Comments