remapping.xml revision 43289eb78809cbdec92c7d90433a8852233f0b2b
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE manualpage SYSTEM "/style/manualpage.dtd">
<?xml-stylesheet type="text/xsl" href="/style/manual.en.xsl"?>
<!-- $LastChangedRevision: 832069 $ -->
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<manualpage metafile="remapping.xml.meta">
<parentdocument href="./">Rewrite</parentdocument>
<title>Redirecting and Remapping with mod_rewrite</title>
<summary>
<p>This document supplements the <module>mod_rewrite</module>
<a href="/mod/mod_rewrite.html">reference documentation</a>. It describes
how you can use <module>mod_rewrite</module> to redirect and remap
request. This includes many examples of common uses of mod_rewrite,
including detailed descriptions of how each works.</p>
<note type="warning">Note that many of these examples won't work unchanged in your
particular server configuration, so it's important that you understand
them, rather than merely cutting and pasting the examples into your
configuration.</note>
</summary>
<seealso><a href="/mod/mod_rewrite.html">Module documentation</a></seealso>
<seealso><a href="intro.html">mod_rewrite introduction</a></seealso>
<!-- <seealso><a href="remapping.html">Redirection and remapping</a></seealso> -->
<seealso><a href="access.html">Controlling access</a></seealso>
<seealso><a href="advanced.html">Advanced techniques and tricks</a></seealso>
<seealso><a href="avoid.html">When not to use mod_rewrite</a></seealso>
<section id="old-to-new">
<title>From Old to New (internal)</title>
<dl>
<dt>Description:</dt>
<dd>
<p>Assume we have recently renamed the page
<code>foo.html</code> to <code>bar.html</code> and now want
to provide the old URL for backward compatibility. However,
we want that users of the old URL even not recognize that
the pages was renamed - that is, we don't want the address to
change in their browser.</p>
</dd>
<dt>Solution:</dt>
<dd>
<p>We rewrite the old URL to the new one internally via the
following rule:</p>
<example><pre>
RewriteEngine on
RewriteRule ^<strong>/old</strong>\.html$ <strong>/new</strong>.html [PT]
</pre></example>
</dd>
</dl>
</section>
<section id="old-to-new-extern">
<title>Rewriting From Old to New (external)</title>
<dl>
<dt>Description:</dt>
<dd>
<p>Assume again that we have recently renamed the page
<code>foo.html</code> to <code>bar.html</code> and now want
to provide the old URL for backward compatibility. But this
time we want that the users of the old URL get hinted to
the new one, i.e. their browsers Location field should
change, too.</p>
</dd>
<dt>Solution:</dt>
<dd>
<p>We force a HTTP redirect to the new URL which leads to a
change of the browsers and thus the users view:</p>
<example><pre>
RewriteEngine on
RewriteRule ^<strong>/foo</strong>\.html$ <strong>bar</strong>.html [<strong>R</strong>]
</pre></example>
</dd>
<dt>Discussion</dt>
<dd>
<p>In this example, as contrasted to the <a
href="#old-to-new-intern">internal</a> example above, we can simply
use the Redirect directive. mod_rewrite was used in that earlier
example in order to hide the redirect from the client:</p>
<example>
Redirect /foo.html /bar.html
</example>
</dd>
</dl>
</section>
<section id="movehomedirs">
<title>Resource Moved to Another Server</title>
<dl>
<dt>Description:</dt>
<dd>
<p>If a resource has moved to another server, you may wish to have
URLs continue to work for a time on the old server while people
update their bookmarks.</p>
</dd>
<dt>Solution:</dt>
<dd>
<p>You can use <module>mod_rewrite</module> to redirect these URLs
to the new server, but you might also consider using the Redirect
or RedirectMatch directive.</p>
<example><title>With mod_rewrite</title><pre>
RewriteEngine on
RewriteRule ^/docs/(.+) http://new.example.com/docs/$1 [R,L]
</pre></example>
<example><title>With RedirectMatch</title><pre>
RedirectMatch ^/docs/(.*) http://new.example.com/docs/$1
</pre></example>
<example><title>With Redirect</title><pre>
Redirect /docs/ http://new.example.com/docs/
</pre></example>
</dd>
</dl>
</section>
<section id="static-to-dynamic">
<title>From Static to Dynamic</title>
<dl>
<dt>Description:</dt>
<dd>
<p>How can we transform a static page
<code>foo.html</code> into a dynamic variant
<code>foo.cgi</code> in a seamless way, i.e. without notice
by the browser/user.</p>
</dd>
<dt>Solution:</dt>
<dd>
<p>We just rewrite the URL to the CGI-script and force the
handler to be <strong>cgi-script</strong> so that it is
executed as a CGI program.
This way a request to <code>/~quux/foo.html</code>
internally leads to the invocation of
<code>/~quux/foo.cgi</code>.</p>
<example><pre>
RewriteEngine on
RewriteBase /~quux/
RewriteRule ^foo\.<strong>html</strong>$ foo.<strong>cgi</strong> [H=<strong>cgi-script</strong>]
</pre></example>
</dd>
</dl>
</section>
<section id="backward-compatibility">
<title>Backward Compatibility for file extension change</title>
<dl>
<dt>Description:</dt>
<dd>
<p>How can we make URLs backward compatible (still
existing virtually) after migrating <code>document.YYYY</code>
to <code>document.XXXX</code>, e.g. after translating a
bunch of <code>.html</code> files to <code>.php</code>?</p>
</dd>
<dt>Solution:</dt>
<dd>
<p>We rewrite the name to its basename and test for
existence of the new extension. If it exists, we take
that name, else we rewrite the URL to its original state.</p>
<example><pre>
# backward compatibility ruleset for
# rewriting document.html to document.php
# when and only when document.php exists
&lt;Directory /var/www/htdocs&gt;
RewriteEngine on
RewriteBase /var/www/htdocs
RewriteCond $1.php -f
RewriteCond $1.html !-f
RewriteRule ^(.*).html$ $1.php
&lt;/Directory&gt;
</pre></example>
</dd>
<dt>Discussion</dt>
<dd>
<p>This example uses an often-overlooked feature of mod_rewrite,
by taking advantage of the order of execution of the ruleset. In
particular, mod_rewrite evaluates the left-hand-side of the
RewriteRule before it evaluates the RewriteCond directives.
Consequently, $1 is already defined by the time the RewriteCond
directives are evaluated. This allows us to test for the existence
of the original (<code>document.html</code>) and target
(<code>document.php</code>) files using the same base filename.</p>
<p>This ruleset is designed to use in a per-directory context (In a
&lt;Directory&gt; block or in a .htaccess file), so that the
<code>-f</code> checks are looking at the correct directory path.
You may need to set a <directive
module="mod_rewite">RewriteBase</directive> directive to specify the
directory base that you're working in.</p>
</dd>
</dl>
</section>
<section id="canonicalhost">
<title>Canonical Hostnames</title>
<dl>
<dt>Description:</dt>
<dd>The goal of this rule is to force the use of a particular
hostname, in preference to other hostnames which may be used to
reach the same site. For example, if you wish to force the use
of <strong>www.example.com</strong> instead of
<strong>example.com</strong>, you might use a variant of the
following recipe.</dd>
<dt>Solution:</dt>
<dd>
<p>For sites running on a port other than 80:</p>
<example><pre>
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{SERVER_PORT} !^80$
RewriteRule ^/?(.*) http://www.example.com:%{SERVER_PORT}/$1 [L,R,NE]
</pre></example>
<p>And for a site running on port 80</p>
<example><pre>
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/?(.*) http://www.example.com/$1 [L,R,NE]
</pre></example>
<p>
If you wanted to do this generically for all domain names - that
is, if you want to redirect <strong>example.com</strong> to
<strong>www.example.com</strong> for all possible values of
<strong>example.com</strong>, you could use the following
recipe:</p>
<example><pre>
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/?(.*) http://www.%{HTTP_HOST}/$1 [L,R,NE]
</pre></example>
<p>These rulesets will work either in your main server configuration
file, or in a <code>.htaccess</code> file placed in the <directive
module="core">DocumentRoot</directive> of the server.</p>
</dd>
</dl>
</section>
<section id="multipledirs">
<title>Search for pages in more than one directory</title>
<dl>
<dt>Description:</dt>
<dd>
<p>A particular resource might exist in one of several places, and
we want to look in those places for the resource when it is
requested. Perhaps we've recently rearranged our directory
structure, dividing content into several locations.</p>
</dd>
<dt>Solution:</dt>
<dd>
<p>The following ruleset searches in two directories to find the
resource, and, if not finding it in either place, will attempt to
just serve it out of the location requested.</p>
<example><pre>
RewriteEngine on
# first try to find it in dir1/...
# ...and if found stop and be happy:
RewriteCond %{DOCUMENT_ROOT}/<strong>dir1</strong>/%{REQUEST_URI} -f
RewriteRule ^(.+) %{DOCUMENT_ROOT}/<strong>dir1</strong>/$1 [L]
# second try to find it in dir2/...
# ...and if found stop and be happy:
RewriteCond %{DOCUMENT_ROOT}/<strong>dir2</strong>/%{REQUEST_URI} -f
RewriteRule ^(.+) %{DOCUMENT_ROOT}/<strong>dir2</strong>/$1 [L]
# else go on for other Alias or ScriptAlias directives,
# etc.
RewriteRule ^(.+) - [PT]
</pre></example>
</dd>
</dl>
</section>
<section id="archive-access-multiplexer">
<title>Redirecting to Geographically Distributed Servers</title>
<dl>
<dt>Description:</dt>
<dd>
<p>We have numerous mirrors of our website, and want to redirect
people to the one that is located in the country where they are
located.</p>
</dd>
<dt>Solution:</dt>
<dd>
<p>Looking at the hostname of the requesting client, we determine
which country they are coming from. If we can't do a lookup on their
IP address, we fall back to a default server.</p>
<p>We'll use a <directive module="mod_rewrite">RewriteMap</directive>
directive to build a list of servers that we wish to use.</p>
<example><pre>
HostnameLookups on
RewriteEngine on
RewriteMap multiplex txt:/path/to/map.mirrors
RewriteCond %{REMOTE_HOST} ([a-z]+)$ [NC]
RewriteRule ^/(.*)$ ${multiplex:<strong>%1</strong>|http://www.example.com/}$1 [R,L]
</pre></example>
<example><pre>
## map.mirrors -- Multiplexing Map
de http://www.example.de/
uk http://www.example.uk/
com http://www.example.com/
##EOF##
</pre></example>
</dd>
<dt>Discussion</dt>
<dd>
<note type="warning">This ruleset relies on
<directive module="core">HostNameLookups</directive>
being set <code>on</code>, which can be
a significant performance hit.</note>
<p>The <directive module="mod_rewrite">RewriteCond</directive>
directive captures the last portion of the hostname of the
requesting client - the country code - and the following RewriteRule
uses that value to look up the appropriate mirror host in the map
file.</p>
</dd>
</dl>
</section>
<section id="browser-dependent-content">
<title>Browser Dependent Content</title>
<dl>
<dt>Description:</dt>
<dd>
<p>We wish to provide different content based on the browser, or
user-agent, which is requesting the content.</p>
</dd>
<dt>Solution:</dt>
<dd>
<p>We have to decide, based on the HTTP header "User-Agent",
which content to serve. The following config
does the following: If the HTTP header "User-Agent"
contains "Mozilla/3", the page <code>foo.html</code>
is rewritten to <code>foo.NS.html</code> and the
rewriting stops. If the browser is "Lynx" or "Mozilla" of
version 1 or 2, the URL becomes <code>foo.20.html</code>.
All other browsers receive page <code>foo.32.html</code>.
This is done with the following ruleset:</p>
<example><pre>
RewriteCond %{HTTP_USER_AGENT} ^<strong>Mozilla/3</strong>.*
RewriteRule ^foo\.html$ foo.<strong>NS</strong>.html [<strong>L</strong>]
RewriteCond %{HTTP_USER_AGENT} ^<strong>Lynx/</strong>.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^<strong>Mozilla/[12]</strong>.*
RewriteRule ^foo\.html$ foo.<strong>20</strong>.html [<strong>L</strong>]
RewriteRule ^foo\.html$ foo.<strong>32</strong>.html [<strong>L</strong>]
</pre></example>
</dd>
</dl>
</section>
<section id="canonicalurl">
<title>Canonical URLs</title>
<dl>
<dt>Description:</dt>
<dd>
<p>On some webservers there is more than one URL for a
resource. Usually there are canonical URLs (which are be
actually used and distributed) and those which are just
shortcuts, internal ones, and so on. Independent of which URL the
user supplied with the request, they should finally see the
canonical one in their browser address bar.</p>
</dd>
<dt>Solution:</dt>
<dd>
<p>We do an external HTTP redirect for all non-canonical
URLs to fix them in the location view of the Browser and
for all subsequent requests. In the example ruleset below
we replace <code>/puppies</code> and <code>/canines</code>
by the canonical <code>/dogs</code>.</p>
<example><pre>
RewriteRule ^/(puppies|canines)/(.*) /dogs/$2 [R]
</pre></example>
</dd>
<dt>Discussion:</dt>
<dd>
This should really be accomplished with Redirect or RedirectMatch
directives:
<example><pre>
RedirectMatch ^/(puppies|canines)/(.*) /dogs/$2
</pre></example>
</dd>
</dl>
</section>
<section id="uservhosts">
<title>Virtual Hosts Per User</title>
<dl>
<dt>Description:</dt>
<dd>
<p>We want to automatically create a virtual host for every user who
has an account on our web server system, without having to create
new VirtualHost sections.</p>
<p>In this recipe, we assume that we'll be using the hostname
<code>www.<strong>username</strong>.example.com</code> for each
user, and serve their content out of
<code>/home/<strong>username</strong>/www</code>.</p>
</dd>
<dt>Solution:</dt>
<dd>
<example><pre>
RewriteEngine on
RewriteCond %{<strong>HTTP_HOST</strong>} ^www\.<strong>([^.]+)</strong>\.example\.com$
RewriteRule ^(.*) /home/<strong>%1</strong>/www$1
</pre></example></dd>
<dt>Discussion</dt>
<dd>
<note type="warning">You will need to take care of the DNS
resolution - Apache does
not handle name resolution. You'll need either to create CNAME
records for each hostname, or a DNS wildcard record. Creating DNS
records is beyond the scope of this document.</note>
<p>Parentheses used in a <directive
module="mod_rewrite">RewriteCond</directive> are captured into the
backreferences <code>%1</code>, <code>%2</code>, etc, while parentheses
used in <directive module="mod_rewrite">RewriteRule</directive> are
captured into the backreferences <code>$1</code>, <code>$2</code>,
etc.</p>
<p>
As with many techniques discussed in this document, mod_rewrite really
isn't the best way to accomplish this task. You should, instead,
consider using <module>mod_vhost_alias</module> instead, as it will much
more gracefully handle anything beyond serving static files, such as any
dynamic content, and Alias resolution.
</p>
</dd>
</dl>
</section>
<section id="moveddocroot">
<title>Moved <code>DocumentRoot</code></title>
<dl>
<dt>Description:</dt>
<dd>
<p>Usually the <directive module="core">DocumentRoot</directive>
of the webserver directly relates to the URL "<code>/</code>".
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 <code>/about/</code>. This may be accomplished
using the following ruleset:</p>
</dd>
<dt>Solution:</dt>
<dd>
<p>We redirect the URL <code>/</code> to
<code>/about/</code>:
</p>
<example><pre>
RewriteEngine on
RewriteRule <strong>^/$</strong> /about/ [<strong>R</strong>]
</pre></example>
<p>Note that this can also be handled using the <directive
module="mod_alias">RedirectMatch</directive> directive:</p>
<example>
RedirectMatch ^/$ http://example.com/about/
</example>
<p>Note also that the example rewrites only the root URL. That is, it
rewrites a request for <code>http://example.com/</code>, but not a
request for <code>http://example.com/page.html</code>. If you have in
fact changed your document root - that is, if <strong>all</strong> of
your content is in fact in that subdirectory, it is greatly preferable
to simply change your <directive module="core">DocumentRoot</directive>
directive, or move all of the content up one directory,
rather than rewriting URLs.</p>
</dd>
</dl>
</section>
<section id="mass-virtual-hosting">
<title>Mass Virtual Hosting</title>
<dl>
<dt>Description:</dt>
<dd>
<p>Mass virtual hosting is one of the more common uses of
mod_rewrite. However, it is seldom the best way to handle mass
virtual hosting. This topic is discussed at great length in the <a
href="/vhosts/mass.html">virtual host documentation</a>.</p>
</dd>
</dl>
</section>
<section id="dynamic-proxy">
<title>Proxying Content with mod_rewrite</title>
<dl>
<dt>Description:</dt>
<dd>
<p>
mod_rewrite provides the [P] flag, which allows URLs to be passed,
via mod_proxy, to another server. Two examples are given here. In
one example, a URL is passed directly to another server, and served
as though it were a local URL. In the other example, we proxy
missing content to a back-end server.</p>
</dd>
<dt>Solution:</dt>
<dd>
<p>To simply map a URL to another server, we use the [P] flag, as
follows:</p>
<example><pre>
RewriteEngine on
RewriteBase /products/
RewriteRule ^<strong>widget/</strong>(.*)$ <strong>http://product.example.com/widget/</strong>$1 [<strong>P</strong>]
ProxyPassReverse /products/widget/ http://product.example.com/widget/
</pre></example>
<p>In the second example, we proxy the request only if we can't find
the resource locally. This can be very useful when you're migrating
from one server to another, and you're not sure if all the content
has been migrated yet.</p>
<example><pre>
RewriteCond %{REQUEST_FILENAME} <strong>!-f</strong>
RewriteCond %{REQUEST_FILENAME} <strong>!-d</strong>
RewriteRule ^/(.*) http://<strong>old</strong>.example.com$1 [<strong>P</strong>]
ProxyPassReverse / http://old.example.com/
</pre></example>
</dd>
<dt>Discussion:</dt>
<dd><p>In each case, we add a <directive
module="mod_proxy">ProxyPassReverse</directive> directive to ensure
that any redirects issued by the backend are correctly passed on to
the client.</p>
<p>Consider using either <directive
module="mod_proxy">ProxyPass</directive> or <directive
module="mod_rewrite">ProxyPassMatch</directive> whenever possible in
preference to mod_rewrite.</p>
</dd>
</dl>
</section>
</manualpage>