Call (877) SITE-OPT (748-3678)

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 home page:


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

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

Copyright © 2002-2018 Website Optimization, LLC. All Rights Reserved - Free website speed test - Privacy Policy
Last modified: February 19, 2009.

Follow us on: Twitter, Google+, Facebook, Linked In