to technology guide

URL Tricks With Apache
07/17/2000

by Edward Piou

mod_rewrite is a fairly powerful Apache module. With it, you can alter the pages which your site visitors go to based on a number of conditions - including username, browser type, and IP address.

The difference between mod_rewrite and mod_alias? For one thing, mod_alias is compiled into Apache by default, while mod_rewrite is not. For another: mod_rewrite lets you use regular expressions and more than just a URL to determine where to send someone on your website.

Here, we'll look at basic use of mod_rewrite, and in future articles, we'll build some pretty powerful applications with it.

To start the typical mod_rewrite set of commands, place the following line in one of your Apache config files (typically httpd.conf, but perhaps srm.conf if you prefer):

RewriteEngine on

This tells Apache that the lines that follow are mod_rewrite directives. The directives you'll probably use will look like this:

RewriteCond %{ENVIRONMENT_VARIABLE} ^VARIABLEVALUE

where you substitute some variable specific to a hit from a browser (HTTP_USER_AGENT, REMOTE_ADDR, etc.) for ENVIRONMENT_VARIABLE, and the value of the variable that you're looking for VARIABLEVALUE. For example, if you want to find all hits from users coming from any IP address that starts with the string "216.112.23":
RewriteCond %{REMOTE_ADDR} ^216.112.23

You can string several conditions together, to catch multiple conditions:

RewriteCond %{REMOTE_ADDR} ^216.112.23 [OR]
RewriteCond %{HTTP_USER_AGENT} ^htdig

would catch both people coming from the IP address range, and all browsers the names of which started with "htdig." To finish things off, you tell Apache what to do with the user using a RewriteRule:
RewriteRule ^.*$ /www/cgis/cgi-ahref/caught.cgi [L,T=application/x-httpd-cgi]

With this RewriteRule, anyone who matched the conditions would be sent to the caught.cgi CGI program.

We'll look at a more powerful use of mod_rewrite in the next article in this series...

Edward Piou is an ahref.com producer and runs ep Productions, Inc., a development company based in the Washington, D.C. area.

to Technology guide

This site copyright 1998-1999 ep Productions, Inc. Text of any articles is copyright of the author.