This document supplements the mod_rewritereference documentation.
It describes how one can use Apache's mod_rewrite
to solve typical URL-based problems with which webmasters are
commonony confronted. We give detailed descriptions on how to
solve each problem by configuring URL rewriting rulesets.
ATTENTION: Depending on your server configuration
it may be necessary to slightly change the examples for your
situation, e.g. adding the [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.
We want to create a homogeneous and consistent URL
layout over all WWW servers on a Intranet webcluster, i.e.
all URLs (per definition server local and thus server
dependent!) become actually server independent!
What we want is to give the WWW namespace a consistent
server-independent layout: no URL should have to include
any physically correct target server. The cluster itself
should drive us automatically to the physical target
host.
Solution:
First, the knowledge of the target servers come from
(distributed) external maps which contain information
where our users, groups and entities stay. The have the
form
user1 server_of_user1
user2 server_of_user2
: :
We put them into files map.xxx-to-host.
Second we need to instruct all servers to redirect URLs
of the forms
when the URL is not locally valid to a server. The
following ruleset does this for us by the help of the map
files (assuming that server0 is a default server which
will be used if a user has no entry in the map):
Some sites with thousands of users usually 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.
Solution:
We use the following ruleset to expand the tilde URLs
into exactly the above layout.
RewriteEngine on
RewriteRule ^/~(([a-z])[a-z0-9]+)(.*) /home/$2/$1/.www$3
This really is a hardcore example: a killer application
which heavily uses per-directory
RewriteRules to get a smooth look and feel
on the Web while its data structure is never touched or
adjusted. Background: net.sw is
my archive of freely available Unix software packages,
which I started to collect in 1992. It is both my hobby
and job to to this, because while I'm studying computer
science I have also worked for many years as a system and
network administrator in my spare time. Every week I need
some sort of software so I created a deep hierarchy of
directories where I stored the packages:
In July 1996 I decided to make this archive public to
the world via a nice Web interface. "Nice" means that I
wanted to offer an interface where you can browse
directly through the archive hierarchy. And "nice" means
that I didn't wanted to change anything inside this
hierarchy - not even by putting some CGI scripts at the
top of it. Why? Because the above structure should be
later accessible via FTP as well, and I didn't want any
Web or CGI stuff to be there.
Solution:
The solution has two parts: The first is a set of CGI
scripts which create all the pages at all directory
levels on-the-fly. I put them under
/e/netsw/.www/ as follows:
-rw-r--r-- 1 netsw users 1318 Aug 1 18:10 .wwwacl
drwxr-xr-x 18 netsw users 512 Aug 5 15:51 DATA/
-rw-rw-rw- 1 netsw users 372982 Aug 5 16:35 LOGFILE
-rw-r--r-- 1 netsw users 659 Aug 4 09:27 TODO
-rw-r--r-- 1 netsw users 5697 Aug 1 18:01 netsw-about.html
-rwxr-xr-x 1 netsw users 579 Aug 2 10:33 netsw-access.pl
-rwxr-xr-x 1 netsw users 1532 Aug 1 17:35 netsw-changes.cgi
-rwxr-xr-x 1 netsw users 2866 Aug 5 14:49 netsw-home.cgi
drwxr-xr-x 2 netsw users 512 Jul 8 23:47 netsw-img/
-rwxr-xr-x 1 netsw users 24050 Aug 5 15:49 netsw-lsdir.cgi
-rwxr-xr-x 1 netsw users 1589 Aug 3 18:43 netsw-search.cgi
-rwxr-xr-x 1 netsw users 1885 Aug 1 17:41 netsw-tree.cgi
-rw-r--r-- 1 netsw users 234 Jul 30 16:35 netsw-unlimit.lst
The DATA/ subdirectory holds the above
directory structure, i.e. the real
net.sw stuff and gets
automatically updated via rdist from time to
time. The second part of the problem remains: how to link
these two structures together into one smooth-looking URL
tree? We want to hide the DATA/ directory
from the user while running the appropriate CGI scripts
for the various URLs. Here is the solution: first I put
the following into the per-directory configuration file
in the DocumentRoot
of the server to rewrite the announced URL
/net.sw/ to the internal path
/e/netsw:
The first rule is for requests which miss the trailing
slash! The second rule does the real thing. And then
comes the killer configuration which stays in the
per-directory config file
/e/netsw/.www/.wwwacl:
Options ExecCGI FollowSymLinks Includes MultiViews
RewriteEngine on
# we are reached via /net.sw/ prefix
RewriteBase /net.sw/
# first we rewrite the root dir to
# the handling cgi script
RewriteRule ^$ netsw-home.cgi [L]
RewriteRule ^index\.html$ netsw-home.cgi [L]
# strip out the subdirs when
# the browser requests us from perdir pages
RewriteRule ^.+/(netsw-[^/]+/.+)$ $1 [L]
# and now break the rewriting for local files
RewriteRule ^netsw-home\.cgi.* - [L]
RewriteRule ^netsw-changes\.cgi.* - [L]
RewriteRule ^netsw-search\.cgi.* - [L]
RewriteRule ^netsw-tree\.cgi$ - [L]
RewriteRule ^netsw-about\.html$ - [L]
RewriteRule ^netsw-img/.*$ - [L]
# anything else is a subdir which gets handled
# by another cgi script
RewriteRule !^netsw-lsdir\.cgi.* - [C]
RewriteRule (.*) netsw-lsdir.cgi/$1
Some hints for interpretation:
Notice the L (last) flag and no
substitution field ('-') in the forth part
Notice the ! (not) character and
the C (chain) flag at the first rule
in the last part
A typical FAQ about URL rewriting is how to redirect
failing requests on webserver A to webserver B. Usually
this is done via ErrorDocument CGI-scripts in Perl, but
there is also a mod_rewrite solution.
But notice that this performs more poorly than using an
ErrorDocument
CGI-script!
Solution:
The first solution has the best performance but less
flexibility, and is less error safe:
RewriteEngine on
RewriteCond /your/docroot/%{REQUEST_FILENAME} !-f
RewriteRule ^(.+) http://webserverB.dom/$1
The problem here is that this will only work for pages
inside the DocumentRoot. While you can add more
Conditions (for instance to also handle homedirs, etc.)
there is better variant:
RewriteEngine on
RewriteCond %{REQUEST_URI} !-U
RewriteRule ^(.+) http://webserverB.dom/$1
This uses the URL look-ahead feature of mod_rewrite.
The result is that this will work for all types of URLs
and is a safe way. But it does a performance impact on
the webserver, because for every request there is one
more internal subrequest. So, if your webserver runs on a
powerful CPU, use this one. If it is a slow machine, use
the first approach or better a ErrorDocument CGI-script.
Archive Access Multiplexer
Описание:
Do you know the great CPAN (Comprehensive Perl Archive
Network) under http://www.perl.com/CPAN?
This does a redirect to one of several FTP servers around
the world which carry a CPAN mirror and is approximately
near the location of the requesting client. Actually this
can be called an FTP access multiplexing service. While
CPAN runs via CGI scripts, how can a similar approach
implemented via mod_rewrite?
Solution:
First we notice that from version 3.0.0
mod_rewrite can
also use the "ftp:" scheme on redirects.
And second, the location approximation can be done by a
RewriteMap
over the top-level domain of the client.
With a tricky chained ruleset we can use this top-level
domain as a key to our multiplexing map.
At least for important top-level pages it is sometimes
necessary to provide the optimum of browser dependent
content, i.e. one has to provide a maximum version for the
latest Netscape variants, a minimum version for the Lynx
browsers and a average feature version for all others.
Solution:
We cannot use content negotiation because the browsers do
not provide their type in that form. Instead we have to
act on the HTTP header "User-Agent". The following condig
does the following: If the HTTP header "User-Agent"
begins with "Mozilla/3", the page foo.html
is rewritten to foo.NS.html and and the
rewriting stops. If the browser is "Lynx" or "Mozilla" of
version 1 or 2 the URL becomes foo.20.html.
All other browsers receive page foo.32.html.
This is done by the following ruleset:
Assume there are nice webpages 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 webserver we could use the program
webcopy which acts similar via HTTP. But both
techniques have one major drawback: The local copy is
always just as up-to-date as often we run the program. It
would be much better if the mirror is not a static one we
have to establish explicitly. Instead we want a dynamic
mirror with data which gets updated automatically when
there is need (updated data on the remote host).
Solution:
To provide this feature we map the remote webpage or even
the complete remote webarea 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]
Reverse Dynamic Mirror
Описание:
...
Solution:
RewriteEngine on
RewriteCond /mirror/of/remotesite/$1 -U
RewriteRule ^http://www\.remotesite\.com/(.*)$ /mirror/of/remotesite/$1
Retrieve Missing Data from Intranet
Описание:
This is a tricky way of virtually running a corporate
(external) Internet webserver
(www.quux-corp.dom), while actually keeping
and maintaining its data on a (internal) Intranet webserver
(www2.quux-corp.dom) which is protected by a
firewall. The trick is that on the external webserver we
retrieve the requested data on-the-fly from the internal
one.
Solution:
First, we have to make sure that our firewall still
protects the internal webserver and that only the
external webserver is allowed to retrieve data from it.
For a packet-filtering firewall we could for instance
configure a firewall ruleset like the following:
ALLOW Host www.quux-corp.dom Port >1024 --> Host www2.quux-corp.dom Port 80DENY 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:
Suppose we want to load balance the traffic to
www.foo.com over www[0-5].foo.com
(a total of 6 servers). How can this be done?
Solution:
There are a lot of possible solutions for this problem.
We will discuss first a commonly known DNS-based variant
and then the special one with mod_rewrite:
DNS Round-Robin
The simplest method for load-balancing is to use
the DNS round-robin feature of BIND.
Here you just configure www[0-9].foo.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 entry:
www IN CNAME www0.foo.com.
IN CNAME www1.foo.com.
IN CNAME www2.foo.com.
IN CNAME www3.foo.com.
IN CNAME www4.foo.com.
IN CNAME www5.foo.com.
IN CNAME www6.foo.com.
Notice that this seems wrong, but is actually an
intended feature of BIND and can be used
in this way. However, now when www.foo.com gets
resolved, BIND gives out www0-www6
- but in a slightly permutated/rotated order every time.
This way the clients are spread over the various
servers. But notice that this not a perfect load
balancing scheme, because DNS resolve information
gets cached by the other nameservers on the net, so
once a client has resolved www.foo.com
to a particular wwwN.foo.com, all
subsequent requests also go to this particular name
wwwN.foo.com. But the final result is
ok, because the total sum of the requests are really
spread over the various webservers.
DNS Load-Balancing
A sophisticated DNS-based method for
load-balancing is to use the program
lbnamed which can be found at
http://www.stanford.edu/~schemers/docs/lbnamed/lbnamed.html.
It is a Perl 5 program in conjunction with auxilliary
tools which provides a real load-balancing for
DNS.
Proxy Throughput Round-Robin
In this variant we use mod_rewrite
and its proxy throughput feature. First we dedicate
www0.foo.com to be actually
www.foo.com by using a single
www IN CNAME www0.foo.com.
entry in the DNS. Then we convert
www0.foo.com to a proxy-only server,
i.e. we configure this machine so all arriving URLs
are just pushed through the 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##
A last notice: Why is this useful? Seems like
www0.foo.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 completely done on the other machines.
This is the essential point.
Hardware/TCP Round-Robin
There is a hardware solution available, too. Cisco
has a beast called LocalDirector which does a load
balancing at the TCP/IP level. Actually this is some
sort of a circuit level gateway in front of a
webcluster. If you have enough money and really need
a solution with high performance, use this one.
New MIME-type, New Service
Описание:
On the net there are a lot of nifty CGI programs. But
their usage is usually boring, so a lot of webmaster
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 we use a Homogeneous URL Layout
(see above) a file inside the user homedirs has the URL
/u/user/foo/bar.scgi. But
cgiwrap needs the URL in the form
/~user/foo/bar.scgi/. The following rule
solves the problem:
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 on which area they have to act on.
But usually this ugly, because they are all the times
still requested from that areas, 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 the area, we spend a
lot of time changing the various hyperlinks.
Solution:
The solution here is to provide a special new URL format
which automatically leads to the proper CGI invocation.
We configure the following:
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.
On-the-fly Content-Regeneration
Описание:
Here comes a really esoteric feature: Dynamically
generated but statically served pages, i.e. pages should be
delivered as pure static pages (read from the filesystem
and just passed through), but they have to be generated
dynamically by the webserver if missing. This way you can
have CGI-generated pages which are statically served unless
one (or a cronjob) removes the static contents. Then the
contents gets refreshed.
Here a request to page.html leads to a
internal run of a corresponding page.cgi if
page.html is still missing or has filesize
null. The trick here is that page.cgi is a
usual CGI script which (additionally to its STDOUT)
writes its output to the file page.html.
Once it was run, the server sends out the data of
page.html. When the webmaster wants to force
a refresh the contents, he just removes
page.html (usually done by a cronjob).
Document With Autorefresh
Описание:
Wouldn't it be nice while creating a complex webpage if
the webbrowser would automatically refresh the page every
time we write a new version from within our editor?
Impossible?
Solution:
No! We just combine the MIME multipart feature, the
webserver NPH feature and the URL manipulation power of
mod_rewrite. First, we establish a new
URL feature: Adding just :refresh to any
URL causes this to be refreshed every time it gets
updated on the filesystem.
The <VirtualHost> feature of Apache is nice
and works great when you just have a few dozens
virtual hosts. But when you are an ISP and have hundreds of
virtual hosts to provide this feature is not the best
choice.
Solution:
To provide this feature we map the remote webpage or even
the complete remote webarea to our namespace by the use
of the Proxy Throughput feature (flag [P]):
##
## 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 puposes
RewriteRule ^/(.*)$ %1/$1 [E=VHOST:${lowercase:%{HTTP_HOST}}]
:
##
## hosts.deny
##
## ATTENTION! This is a map, not a list, even when we treat it as such.
## mod_rewrite parses it for key/value pairs, so at least a
## dummy value "-" must be present for each entry.
##
193.102.180.41 -
bsdti1.sdm.de -
192.76.162.40 -
Proxy Deny
Описание:
How can we forbid a certain host or even a user of a
special host from using the Apache proxy?
Solution:
We first have to make sure mod_rewrite
is below(!) mod_proxy in the Configuration
file when compiling the Apache webserver. This way it gets
called beforemod_proxy. Then we
configure the following for a host-dependent deny...
Sometimes a very special authentication is needed, for
instance a authentication which checks for a set of
explicitly configured users. Only these should receive
access and without explicit prompting (which would occur
when using the Basic Auth via mod_auth).
Solution:
We use a list of rewrite conditions to exclude all except
our friends:
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).