Code: mod_rewrite rewritemap

Chapter 9 - Advanced Web Performance Optimization

RewriteMaps group multiple lookup keys (abbreviations) and their corresponding expanded values into one tab-delimited file. Here's an example map file snippet from the Yahoo.com home page:

r/4d http://answers.yahoo.com/
r/2h http://autos.yahoo.com/
r/25 http://finance.yahoo.com/
r/26 http://sports.yahoo.com/
r/29 http://travel.yahoo.com/
...

The MapName file maps keys to values for a rewrite rule using the following syntax:

${ MapName : LookupKey | DefaultValue }

MapNames require a generalized RewriteRule using regular expressions. The RewriteRule references the MapName instead of a hardcoded value. If there is a key match, the mapping function substitutes the expanded value into the regular expression. If there's no match, the rule substitutes a default value or a blank string.

To use this MapName we need a RewriteMap directive to show where the mapping file is, and a generalized regular expression for our RewriteRule:

RewriteEngine On
RewriteMap abbr txt:/www/misc/redir/abbr_yahoo.txt
RewriteRule ^/r/([^/]*)/?(.*) $(abbr:$1}$2 [R=301,L]

The new RewriteMap rule points the rewrite module to the text version of our map file. The revamped RewriteRule looks up the value for matching keys in the map file. The permanent redirect (301 instead of 302) boosts performance by stopping processing once the matching abbreviation is found in the map file.

Binary hash RewriteMaps

For maximum speed, you should convert your text map files into a binary *DBM hash file, which is optimized for maximum lookup speed. To create a DBM file from a source text file, use the httxt2dbm utility:

$ httxt2dbm -i abbr_yahoo.txt -o abbr_yanoo.map

As such, the earlier RewriteMap line would look like this:

RewriteMap abbr txt:/www/misc/redir/abbr_yahoo

Yahoo! saves nearly 30% off its home page HTML with this technique. Yahoo! also uses subdomains, which helps to redistribute the load. For more details on using mod_rewrite, see the Apache documentation at http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritemap.