Apache HTTP Server Version 2.3

This document supplements the mod_rewrite
reference documentation.
It describes how one can use Apache's mod_rewrite
to solve typical URL-based problems with which webmasters are
commonly confronted. We give detailed descriptions on how to
solve each problem by configuring URL rewriting rulesets.
[PT] flag when
additionally using mod_alias and
mod_userdir, etc. Or rewriting a ruleset
to fit in .htaccess context instead
of per-server context. Always try to understand what a
particular ruleset really does before you use it. This
avoids many problems.
Moved DocumentRoot
Trailing Slash Problem
Set Environment Variables According To URL Parts
Virtual Hosts Per User
Redirect Homedirs For Foreigners
Redirecting Anchors
Time-Dependent Rewriting
External Rewriting Engine
Structured Homedirs
Dynamic Mirror
Retrieve Missing Data from Intranet
Load Balancing
New MIME-type, New Service
Document With Autorefresh
Mass Virtual Hosting
Proxy Deny
Referer-based DeflectorDocumentRootUsually the DocumentRoot
of the webserver directly relates to the URL "/".
But often this data is not really of top-level priority. For example,
you may wish for visitors, on first entering a site, to go to a
particular subdirectory /about/. This may be accomplished
using the following ruleset:
We redirect the URL / to
/about/:
RewriteEngine on RewriteRule ^/$ /about/ [R]
Note that this can also be handled using the RedirectMatch directive:
RedirectMatch ^/$ http://example.com/about/
Note also that the example rewrites only the root URL. That is, it
rewrites a request for http://example.com/, but not a
request for http://example.com/page.html. If you have in
fact changed your document root - that is, if all of
your content is in fact in that subdirectory, it is greatly preferable
to simply change your DocumentRoot
directive, rather than rewriting URLs.
The vast majority of "trailing slash" problems can be dealt with using the techniques discussed in the FAQ entry. However, occasionally, there is a need to use mod_rewrite to handle a case where a missing trailing slash causes a URL to fail. This can happen, for example, after a series of complex rewrite rules.
The solution to this subtle problem is to let the server
add the trailing slash automatically. To do this
correctly we have to use an external redirect, so the
browser correctly requests subsequent images etc. If we
only did a internal rewrite, this would only work for the
directory page, but would go wrong when any images are
included into this page with relative URLs, because the
browser would request an in-lined object. For instance, a
request for image.gif in
/~quux/foo/index.html would become
/~quux/image.gif without the external
redirect!
So, to do this trick we write:
RewriteEngine on RewriteBase /~quux/ RewriteRule ^foo$ foo/ [R]
Alternately, you can put the following in a
top-level .htaccess file in the content directory.
But note that this creates some processing overhead.
RewriteEngine on
RewriteBase /~quux/
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+[^/])$ $1/ [R]
Perhaps you want to keep status information between requests and use the URL to encode it. But you don't want to use a CGI wrapper for all pages just to strip out this information.
We use a rewrite rule to strip out the status information
and remember it via an environment variable which can be
later dereferenced from within XSSI or CGI. This way a
URL /foo/S=java/bar/ gets translated to
/foo/bar/ and the environment variable named
STATUS is set to the value "java".
RewriteEngine on RewriteRule ^(.*)/S=([^/]+)/(.*) $1/$3 [E=STATUS:$2]
Assume that you want to provide
www.username.host.domain.com
for the homepage of username via just DNS A records to the
same machine and without any virtualhosts on this
machine.
For HTTP/1.0 requests there is no solution, but for
HTTP/1.1 requests which contain a Host: HTTP header we
can use the following ruleset to rewrite
http://www.username.host.com/anypath
internally to /home/username/anypath:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.([^.]+)\.host\.com$
RewriteRule ^(.*) /home/%1$1
Parentheses used in a RewriteCond are captured into the
backreferences %1, %2, etc, while parentheses
used in RewriteRule are
captured into the backreferences $1, $2,
etc.
We want to redirect homedir URLs to another webserver
www.somewhere.com when the requesting user
does not stay in the local domain
ourdomain.com. This is sometimes used in
virtual host contexts.
Just a rewrite condition:
RewriteEngine on
RewriteCond %{REMOTE_HOST} !^.+\.ourdomain\.com$
RewriteRule ^(/~.+) http://www.somewhere.com/$1 [R,L]
By default, redirecting to an HTML anchor doesn't work,
because mod_rewrite escapes the # character,
turning it into %23. This, in turn, breaks the
redirection.
Use the [NE] flag on the
RewriteRule. NE stands for No Escape.
When tricks like time-dependent content should happen a
lot of webmasters still use CGI scripts which do for
instance redirects to specialized pages. How can it be done
via mod_rewrite?
There are a lot of variables named TIME_xxx
for rewrite conditions. In conjunction with the special
lexicographic comparison patterns <STRING,
>STRING and =STRING we can
do time-dependent redirects:
RewriteEngine on
RewriteCond %{TIME_HOUR}%{TIME_MIN} >0700
RewriteCond %{TIME_HOUR}%{TIME_MIN} <1900
RewriteRule ^foo\.html$ foo.day.html
RewriteRule ^foo\.html$ foo.night.html
This provides the content of foo.day.html
under the URL foo.html from
07:01-18:59 and at the remaining time the
contents of foo.night.html. Just a nice
feature for a homepage...
mod_cache, intermediate proxies
and browsers may each cache responses and cause the either page to be
shown outside of the time-window configured.
mod_expires may be used to control this
effect.A FAQ: How can we solve the FOO/BAR/QUUX/etc.
problem? There seems no solution by the use of
mod_rewrite...
Use an external RewriteMap, i.e. a program which acts
like a RewriteMap. It is run once on startup of Apache
receives the requested URLs on STDIN and has
to put the resulting (usually rewritten) URL on
STDOUT (same order!).
RewriteEngine on
RewriteMap quux-map prg:/path/to/map.quux.pl
RewriteRule ^/~quux/(.*)$ /~quux/${quux-map:$1}
#!/path/to/perl
# disable buffered I/O which would lead
# to deadloops for the Apache server
$| = 1;
# read URLs one per line from stdin and
# generate substitution URL on stdout
while (<>) {
s|^foo/|bar/|;
print $_;
}
This is a demonstration-only example and just rewrites
all URLs /~quux/foo/... to
/~quux/bar/.... Actually you can program
whatever you like. But notice that while such maps can be
used also by an average user, only the
system administrator can define it.
Some sites with thousands of users use a
structured homedir layout, i.e. each homedir is in a
subdirectory which begins (for instance) with the first
character of the username. So, /~foo/anypath
is /home/f/foo/.www/anypath
while /~bar/anypath is
/home/b/bar/.www/anypath.
We use the following ruleset to expand the tilde URLs into the above layout.
RewriteEngine on RewriteRule ^/~(([a-z])[a-z0-9]+)(.*) /home/$2/$1/.www$3
Assume there are nice web pages on remote hosts we want
to bring into our namespace. For FTP servers we would use
the mirror program which actually maintains an
explicit up-to-date copy of the remote data on the local
machine. For a web server we could use the program
webcopy which runs via HTTP. But both
techniques have a major drawback: The local copy is
always only as up-to-date as the last time we ran the program. It
would be much better if the mirror was not a static one we
have to establish explicitly. Instead we want a dynamic
mirror with data which gets updated automatically
as needed on the remote host(s).
To provide this feature we map the remote web page or even
the complete remote web area to our namespace by the use
of the Proxy Throughput feature
(flag [P]):
RewriteEngine on RewriteBase /~quux/ RewriteRule ^hotsheet/(.*)$ http://www.tstimpreso.com/hotsheet/$1 [P]
RewriteEngine on RewriteBase /~quux/ RewriteRule ^usa-news\.html$ http://www.quux-corp.com/news/index.html [P]
This is a tricky way of virtually running a corporate
(external) Internet web server
(www.quux-corp.dom), while actually keeping
and maintaining its data on an (internal) Intranet web server
(www2.quux-corp.dom) which is protected by a
firewall. The trick is that the external web server retrieves
the requested data on-the-fly from the internal
one.
First, we must make sure that our firewall still protects the internal web server and only the external web server is allowed to retrieve data from it. On a packet-filtering firewall, for instance, we could configure a firewall ruleset like the following:
ALLOW Host www.quux-corp.dom Port >1024 --> Host www2.quux-corp.dom Port 80 DENY Host * Port * --> Host www2.quux-corp.dom Port 80
Just adjust it to your actual configuration syntax.
Now we can establish the mod_rewrite
rules which request the missing data in the background
through the proxy throughput feature:
RewriteRule ^/~([^/]+)/?(.*) /home/$1/.www/$2 [C]
# REQUEST_FILENAME usage below is correct in this per-server context example
# because the rule that references REQUEST_FILENAME is chained to a rule that
# sets REQUEST_FILENAME.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/home/([^/]+)/.www/?(.*) http://www2.quux-corp.dom/~$1/pub/$2 [P]
Suppose we want to load balance the traffic to
www.example.com over www[0-5].example.com
(a total of 6 servers). How can this be done?
There are many possible solutions for this problem.
We will first discuss a common DNS-based method,
and then one based on mod_rewrite:
The simplest method for load-balancing is to use
DNS round-robin.
Here you just configure www[0-9].example.com
as usual in your DNS with A (address) records, e.g.,
www0 IN A 1.2.3.1 www1 IN A 1.2.3.2 www2 IN A 1.2.3.3 www3 IN A 1.2.3.4 www4 IN A 1.2.3.5 www5 IN A 1.2.3.6
Then you additionally add the following entries:
www IN A 1.2.3.1 www IN A 1.2.3.2 www IN A 1.2.3.3 www IN A 1.2.3.4 www IN A 1.2.3.5
Now when www.example.com gets
resolved, BIND gives out www0-www5
- but in a permutated (rotated) order every time.
This way the clients are spread over the various
servers. But notice that this is not a perfect load
balancing scheme, because DNS resolutions are
cached by clients and other nameservers, so
once a client has resolved www.example.com
to a particular wwwN.example.com, all its
subsequent requests will continue to go to the same
IP (and thus a single server), rather than being
distributed across the other available servers. But the
overall result is
okay because the requests are collectively
spread over the various web servers.
A sophisticated DNS-based method for
load-balancing is to use the program
lbnamed which can be found at
http://www.stanford.edu/~riepel/lbnamed/.
It is a Perl 5 program which, in conjunction with auxiliary
tools, provides real load-balancing via
DNS.
In this variant we use mod_rewrite
and its proxy throughput feature. First we dedicate
www0.example.com to be actually
www.example.com by using a single
www IN CNAME www0.example.com.
entry in the DNS. Then we convert
www0.example.com to a proxy-only server,
i.e., we configure this machine so all arriving URLs
are simply passed through its internal proxy to one of
the 5 other servers (www1-www5). To
accomplish this we first establish a ruleset which
contacts a load balancing script lb.pl
for all URLs.
RewriteEngine on
RewriteMap lb prg:/path/to/lb.pl
RewriteRule ^/(.+)$ ${lb:$1} [P,L]
Then we write lb.pl:
#!/path/to/perl
##
## lb.pl -- load balancing script
##
$| = 1;
$name = "www"; # the hostname base
$first = 1; # the first server (not 0 here, because 0 is myself)
$last = 5; # the last server in the round-robin
$domain = "foo.dom"; # the domainname
$cnt = 0;
while (<STDIN>) {
$cnt = (($cnt+1) % ($last+1-$first));
$server = sprintf("%s%d.%s", $name, $cnt+$first, $domain);
print "http://$server/$_";
}
##EOF##
www0.example.com still is overloaded? The
answer is yes, it is overloaded, but with plain proxy
throughput requests, only! All SSI, CGI, ePerl, etc.
processing is handled done on the other machines.
For a complicated site, this may work well. The biggest
risk here is that www0 is now a single point of failure --
if it crashes, the other servers are inaccessible.There are more sophisticated solutions, as well. Cisco, F5, and several other companies sell hardware load balancers (typically used in pairs for redundancy), which offer sophisticated load balancing and auto-failover features. There are software packages which offer similar features on commodity hardware, as well. If you have enough money or need, check these out. The lb-l mailing list is a good place to research.
On the net there are many nifty CGI programs. But
their usage is usually boring, so a lot of webmasters
don't use them. Even Apache's Action handler feature for
MIME-types is only appropriate when the CGI programs
don't need special URLs (actually PATH_INFO
and QUERY_STRINGS) as their input. First,
let us configure a new file type with extension
.scgi (for secure CGI) which will be processed
by the popular cgiwrap program. The problem
here is that for instance if we use a Homogeneous URL Layout
(see above) a file inside the user homedirs might have a URL
like /u/user/foo/bar.scgi, but
cgiwrap needs URLs in the form
/~user/foo/bar.scgi/. The following rule
solves the problem:
RewriteRule ^/[uge]/([^/]+)/\.www/(.+)\.scgi(.*) ... ... /internal/cgi/user/cgiwrap/~$1/$2.scgi$3 [NS,T=application/x-http-cgi]
Or assume we have some more nifty programs:
wwwlog (which displays the
access.log for a URL subtree) and
wwwidx (which runs Glimpse on a URL
subtree). We have to provide the URL area to these
programs so they know which area they are really working with.
But usually this is complicated, because they may still be
requested by the alternate URL form, i.e., typically we would
run the swwidx program from within
/u/user/foo/ via hyperlink to
/internal/cgi/user/swwidx?i=/u/user/foo/
which is ugly, because we have to hard-code both the location of the area and the location of the CGI inside the hyperlink. When we have to reorganize, we spend a lot of time changing the various hyperlinks.
The solution here is to provide a special new URL format which automatically leads to the proper CGI invocation. We configure the following:
RewriteRule ^/([uge])/([^/]+)(/?.*)/\* /internal/cgi/user/wwwidx?i=/$1/$2$3/ RewriteRule ^/([uge])/([^/]+)(/?.*):log /internal/cgi/user/wwwlog?f=/$1/$2$3
Now the hyperlink to search at
/u/user/foo/ reads only
HREF="*"
which internally gets automatically transformed to
/internal/cgi/user/wwwidx?i=/u/user/foo/
The same approach leads to an invocation for the
access log CGI program when the hyperlink
:log gets used.
Wouldn't it be nice, while creating a complex web page, if the web browser would automatically refresh the page every time we save a new version from within our editor? Impossible?
No! We just combine the MIME multipart feature, the
web server NPH feature, and the URL manipulation power of
mod_rewrite. First, we establish a new
URL feature: Adding just :refresh to any
URL causes the 'page' to be refreshed every time it is
updated on the filesystem.
RewriteRule ^(/[uge]/[^/]+/?.*):refresh /internal/cgi/apache/nph-refresh?f=$1
Now when we reference the URL
/u/foo/bar/page.html:refresh
this leads to the internal invocation of the URL
/internal/cgi/apache/nph-refresh?f=/u/foo/bar/page.html
The only missing part is the NPH-CGI script. Although one would usually say "left as an exercise to the reader" ;-) I will provide this, too.
#!/sw/bin/perl
##
## nph-refresh -- NPH/CGI script for auto refreshing pages
## Copyright (c) 1997 Ralf S. Engelschall, All Rights Reserved.
##
$| = 1;
# split the QUERY_STRING variable
@pairs = split(/&/, $ENV{'QUERY_STRING'});
foreach $pair (@pairs) {
($name, $value) = split(/=/, $pair);
$name =~ tr/A-Z/a-z/;
$name = 'QS_' . $name;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
eval "\$$name = \"$value\"";
}
$QS_s = 1 if ($QS_s eq '');
$QS_n = 3600 if ($QS_n eq '');
if ($QS_f eq '') {
print "HTTP/1.0 200 OK\n";
print "Content-type: text/html\n\n";
print "<b>ERROR</b>: No file given\n";
exit(0);
}
if (! -f $QS_f) {
print "HTTP/1.0 200 OK\n";
print "Content-type: text/html\n\n";
print "<b>ERROR</b>: File $QS_f not found\n";
exit(0);
}
sub print_http_headers_multipart_begin {
print "HTTP/1.0 200 OK\n";
$bound = "ThisRandomString12345";
print "Content-type: multipart/x-mixed-replace;boundary=$bound\n";
&print_http_headers_multipart_next;
}
sub print_http_headers_multipart_next {
print "\n--$bound\n";
}
sub print_http_headers_multipart_end {
print "\n--$bound--\n";
}
sub displayhtml {
local($buffer) = @_;
$len = length($buffer);
print "Content-type: text/html\n";
print "Content-length: $len\n\n";
print $buffer;
}
sub readfile {
local($file) = @_;
local(*FP, $size, $buffer, $bytes);
($x, $x, $x, $x, $x, $x, $x, $size) = stat($file);
$size = sprintf("%d", $size);
open(FP, "<$file");
$bytes = sysread(FP, $buffer, $size);
close(FP);
return $buffer;
}
$buffer = &readfile($QS_f);
&print_http_headers_multipart_begin;
&displayhtml($buffer);
sub mystat {
local($file) = $_[0];
local($time);
($x, $x, $x, $x, $x, $x, $x, $x, $x, $mtime) = stat($file);
return $mtime;
}
$mtimeL = &mystat($QS_f);
$mtime = $mtime;
for ($n = 0; $n < $QS_n; $n++) {
while (1) {
$mtime = &mystat($QS_f);
if ($mtime ne $mtimeL) {
$mtimeL = $mtime;
sleep(2);
$buffer = &readfile($QS_f);
&print_http_headers_multipart_next;
&displayhtml($buffer);
sleep(5);
$mtimeL = &mystat($QS_f);
last;
}
sleep($QS_s);
}
}
&print_http_headers_multipart_end;
exit(0);
##EOF##
The <VirtualHost> feature of Apache is nice
and works great when you just have a few dozen
virtual hosts. But when you are an ISP and have hundreds of
virtual hosts, this feature is suboptimal.
To provide this feature we map the remote web page or even
the complete remote web area to our namespace using the
Proxy Throughput feature (flag [P]):
##
## vhost.map
##
www.vhost1.dom:80 /path/to/docroot/vhost1
www.vhost2.dom:80 /path/to/docroot/vhost2
:
www.vhostN.dom:80 /path/to/docroot/vhostN
##
## httpd.conf
##
:
# use the canonical hostname on redirects, etc.
UseCanonicalName on
:
# add the virtual host in front of the CLF-format
CustomLog /path/to/access_log "%{VHOST}e %h %l %u %t \"%r\" %>s %b"
:
# enable the rewriting engine in the main server
RewriteEngine on
# define two maps: one for fixing the URL and one which defines
# the available virtual hosts with their corresponding
# DocumentRoot.
RewriteMap lowercase int:tolower
RewriteMap vhost txt:/path/to/vhost.map
# Now do the actual virtual host mapping
# via a huge and complicated single rule:
#
# 1. make sure we don't map for common locations
RewriteCond %{REQUEST_URI} !^/commonurl1/.*
RewriteCond %{REQUEST_URI} !^/commonurl2/.*
:
RewriteCond %{REQUEST_URI} !^/commonurlN/.*
#
# 2. make sure we have a Host header, because
# currently our approach only supports
# virtual hosting through this header
RewriteCond %{HTTP_HOST} !^$
#
# 3. lowercase the hostname
RewriteCond ${lowercase:%{HTTP_HOST}|NONE} ^(.+)$
#
# 4. lookup this hostname in vhost.map and
# remember it only when it is a path
# (and not "NONE" from above)
RewriteCond ${vhost:%1} ^(/.*)$
#
# 5. finally we can map the URL to its docroot location
# and remember the virtual host for logging purposes
RewriteRule ^/(.*)$ %1/$1 [E=VHOST:${lowercase:%{HTTP_HOST}}]
:
How can we forbid a certain host or even a user of a special host from using the Apache proxy?
We first have to make sure mod_rewrite
is below(!) mod_proxy in the Configuration
file when compiling the Apache web server. This way it gets
called before mod_proxy. Then we
configure the following for a host-dependent deny...
RewriteCond %{REMOTE_HOST} ^badhost\.mydomain\.com$
RewriteRule !^http://[^/.]\.mydomain.com.* - [F]
...and this one for a user@host-dependent deny:
RewriteCond %{REMOTE_IDENT}@%{REMOTE_HOST} ^badguy@badhost\.mydomain\.com$
RewriteRule !^http://[^/.]\.mydomain.com.* - [F]
How can we program a flexible URL Deflector which acts on the "Referer" HTTP header and can be configured with as many referring pages as we like?
Use the following really tricky ruleset...
RewriteMap deflector txt:/path/to/deflector.map
RewriteCond %{HTTP_REFERER} !=""
RewriteCond ${deflector:%{HTTP_REFERER}} ^-$
RewriteRule ^.* %{HTTP_REFERER} [R,L]
RewriteCond %{HTTP_REFERER} !=""
RewriteCond ${deflector:%{HTTP_REFERER}|NOT-FOUND} !=NOT-FOUND
RewriteRule ^.* ${deflector:%{HTTP_REFERER}} [R,L]
... in conjunction with a corresponding rewrite map:
## ## deflector.map ## http://www.badguys.com/bad/index.html - http://www.badguys.com/bad/index2.html - http://www.badguys.com/bad/index3.html http://somewhere.com/
This automatically redirects the request back to the
referring page (when "-" is used as the value
in the map) or to a specific URL (when an URL is specified
in the map as the second argument).