1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE manualpage SYSTEM "../style/manualpage.dtd">
3 <?xml-stylesheet type="text/xsl" href="../style/manual.en.xsl"?>
4 <!-- $LastChangedRevision$ -->
7 Licensed to the Apache Software Foundation (ASF) under one or more
8 contributor license agreements. See the NOTICE file distributed with
9 this work for additional information regarding copyright ownership.
10 The ASF licenses this file to You under the Apache License, Version 2.0
11 (the "License"); you may not use this file except in compliance with
12 the License. You may obtain a copy of the License at
14 http://www.apache.org/licenses/LICENSE-2.0
16 Unless required by applicable law or agreed to in writing, software
17 distributed under the License is distributed on an "AS IS" BASIS,
18 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 See the License for the specific language governing permissions and
20 limitations under the License.
23 <manualpage metafile="remapping.xml.meta">
24 <parentdocument href="./">Rewrite</parentdocument>
26 <title>Redirecting and Remapping with mod_rewrite</title>
30 <p>This document supplements the <module>mod_rewrite</module>
31 <a href="../mod/mod_rewrite.html">reference documentation</a>. It describes
32 how you can use <module>mod_rewrite</module> to redirect and remap
33 request. This includes many examples of common uses of mod_rewrite,
34 including detailed descriptions of how each works.</p>
36 <note type="warning">Note that many of these examples won't work unchanged in your
37 particular server configuration, so it's important that you understand
38 them, rather than merely cutting and pasting the examples into your
42 <seealso><a href="../mod/mod_rewrite.html">Module documentation</a></seealso>
43 <seealso><a href="intro.html">mod_rewrite introduction</a></seealso>
44 <!--<seealso><a href="remapping.html">Redirection and remapping</a></seealso>-->
45 <seealso><a href="access.html">Controlling access</a></seealso>
46 <seealso><a href="vhosts.html">Virtual hosts</a></seealso>
47 <seealso><a href="proxy.html">Proxying</a></seealso>
48 <seealso><a href="rewritemap.html">Using RewriteMap</a></seealso>
49 <seealso><a href="advanced.html">Advanced techniques</a></seealso>
50 <seealso><a href="avoid.html">When not to use mod_rewrite</a></seealso>
52 <section id="old-to-new">
54 <title>From Old to New (internal)</title>
60 <p>Assume we have recently renamed the page
61 <code>foo.html</code> to <code>bar.html</code> and now want
62 to provide the old URL for backward compatibility. However,
63 we want that users of the old URL even not recognize that
64 the pages was renamed - that is, we don't want the address to
65 change in their browser.</p>
71 <p>We rewrite the old URL to the new one internally via the
74 <highlight language="config">
76 RewriteRule ^<strong>/foo</strong>\.html$ <strong>/bar</strong>.html [PT]
83 <section id="old-to-new-extern">
85 <title>Rewriting From Old to New (external)</title>
91 <p>Assume again that we have recently renamed the page
92 <code>foo.html</code> to <code>bar.html</code> and now want
93 to provide the old URL for backward compatibility. But this
94 time we want that the users of the old URL get hinted to
95 the new one, i.e. their browsers Location field should
102 <p>We force a HTTP redirect to the new URL which leads to a
103 change of the browsers and thus the users view:</p>
105 <highlight language="config">
107 RewriteRule ^<strong>/foo</strong>\.html$ <strong>bar</strong>.html [<strong>R</strong>]
114 <p>In this example, as contrasted to the <a
115 href="#old-to-new-intern">internal</a> example above, we can simply
116 use the Redirect directive. mod_rewrite was used in that earlier
117 example in order to hide the redirect from the client:</p>
119 <highlight language="config">
120 Redirect "/foo.html" "/bar.html"
128 <section id="movehomedirs">
130 <title>Resource Moved to Another Server</title>
133 <dt>Description:</dt>
136 <p>If a resource has moved to another server, you may wish to have
137 URLs continue to work for a time on the old server while people
138 update their bookmarks.</p>
144 <p>You can use <module>mod_rewrite</module> to redirect these URLs
145 to the new server, but you might also consider using the Redirect
146 or RedirectMatch directive.</p>
148 <highlight language="config">
151 RewriteRule ^/docs/(.+) http://new.example.com/docs/$1 [R,L]
154 <highlight language="config">
156 RedirectMatch "^/docs/(.*)" "http://new.example.com/docs/$1"
159 <highlight language="config">
161 Redirect "/docs/" "http://new.example.com/docs/"
168 <section id="static-to-dynamic">
170 <title>From Static to Dynamic</title>
173 <dt>Description:</dt>
176 <p>How can we transform a static page
177 <code>foo.html</code> into a dynamic variant
178 <code>foo.cgi</code> in a seamless way, i.e. without notice
179 by the browser/user.</p>
185 <p>We just rewrite the URL to the CGI-script and force the
186 handler to be <strong>cgi-script</strong> so that it is
187 executed as a CGI program.
188 This way a request to <code>/~quux/foo.html</code>
189 internally leads to the invocation of
190 <code>/~quux/foo.cgi</code>.</p>
192 <highlight language="config">
195 RewriteRule ^foo\.html$ foo.cgi [H=<strong>cgi-script</strong>]
202 <section id="backward-compatibility">
204 <title>Backward Compatibility for file extension change</title>
207 <dt>Description:</dt>
210 <p>How can we make URLs backward compatible (still
211 existing virtually) after migrating <code>document.YYYY</code>
212 to <code>document.XXXX</code>, e.g. after translating a
213 bunch of <code>.html</code> files to <code>.php</code>?</p>
219 <p>We rewrite the name to its basename and test for
220 existence of the new extension. If it exists, we take
221 that name, else we rewrite the URL to its original state.</p>
223 <highlight language="config">
224 # backward compatibility ruleset for
225 # rewriting document.html to document.php
226 # when and only when document.php exists
227 <Directory "/var/www/htdocs">
229 RewriteBase /var/www/htdocs
231 RewriteCond $1.php -f
232 RewriteCond $1.html !-f
233 RewriteRule ^(.*).html$ $1.php
240 <p>This example uses an often-overlooked feature of mod_rewrite,
241 by taking advantage of the order of execution of the ruleset. In
242 particular, mod_rewrite evaluates the left-hand-side of the
243 RewriteRule before it evaluates the RewriteCond directives.
244 Consequently, $1 is already defined by the time the RewriteCond
245 directives are evaluated. This allows us to test for the existence
246 of the original (<code>document.html</code>) and target
247 (<code>document.php</code>) files using the same base filename.</p>
249 <p>This ruleset is designed to use in a per-directory context (In a
250 <Directory> block or in a .htaccess file), so that the
251 <code>-f</code> checks are looking at the correct directory path.
252 You may need to set a <directive
253 module="mod_rewrite">RewriteBase</directive> directive to specify the
254 directory base that you're working in.</p>
260 <section id="canonicalhost">
262 <title>Canonical Hostnames</title>
265 <dt>Description:</dt>
267 <dd>The goal of this rule is to force the use of a particular
268 hostname, in preference to other hostnames which may be used to
269 reach the same site. For example, if you wish to force the use
270 of <strong>www.example.com</strong> instead of
271 <strong>example.com</strong>, you might use a variant of the
272 following recipe.</dd>
278 <p>The very best way to solve this doesn't involve mod_rewrite at all,
279 but rather uses the <directive module="mod_alias">Redirect</directive>
280 directive placed in a virtual host for the non-canonical
283 <highlight language="config">
284 <VirtualHost *:80>
285 ServerName undesired.example.com
286 ServerAlias example.com notthis.example.com
288 Redirect "/" "http://www.example.com/"
291 <VirtualHost *:80>
292 ServerName www.example.com
296 <p>You can alternatively accomplish this using the
297 <directive module="core" type="section">If</directive>
300 <highlight language="config">
301 <If "%{HTTP_HOST} != 'www.example.com'">
302 Redirect "/" "http://www.example.com/"
306 <p>Or, for example, to redirect a portion of your site to HTTPS, you
307 might do the following:</p>
309 <highlight language="config">
310 <If "%{SERVER_PROTOCOL} != 'HTTPS'">
311 Redirect "/admin/" "https://www.example.com/admin/"
315 <p>If, for whatever reason, you still want to use <code>mod_rewrite</code>
316 - if, for example, you need this to work with a larger set of RewriteRules -
317 you might use one of the recipes below.</p>
319 <p>For sites running on a port other than 80:</p>
320 <highlight language="config">
321 RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
322 RewriteCond %{HTTP_HOST} !^$
323 RewriteCond %{SERVER_PORT} !^80$
324 RewriteRule ^/?(.*) http://www.example.com:%{SERVER_PORT}/$1 [L,R,NE]
327 <p>And for a site running on port 80</p>
328 <highlight language="config">
329 RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
330 RewriteCond %{HTTP_HOST} !^$
331 RewriteRule ^/?(.*) http://www.example.com/$1 [L,R,NE]
335 If you wanted to do this generically for all domain names - that
336 is, if you want to redirect <strong>example.com</strong> to
337 <strong>www.example.com</strong> for all possible values of
338 <strong>example.com</strong>, you could use the following
341 <highlight language="config">
342 RewriteCond %{HTTP_HOST} !^www\. [NC]
343 RewriteCond %{HTTP_HOST} !^$
344 RewriteRule ^/?(.*) http://www.%{HTTP_HOST}/$1 [L,R,NE]
347 <p>These rulesets will work either in your main server configuration
348 file, or in a <code>.htaccess</code> file placed in the <directive
349 module="core">DocumentRoot</directive> of the server.</p>
355 <section id="multipledirs">
357 <title>Search for pages in more than one directory</title>
360 <dt>Description:</dt>
363 <p>A particular resource might exist in one of several places, and
364 we want to look in those places for the resource when it is
365 requested. Perhaps we've recently rearranged our directory
366 structure, dividing content into several locations.</p>
372 <p>The following ruleset searches in two directories to find the
373 resource, and, if not finding it in either place, will attempt to
374 just serve it out of the location requested.</p>
376 <highlight language="config">
379 # first try to find it in dir1/...
380 # ...and if found stop and be happy:
381 RewriteCond %{DOCUMENT_ROOT}/<strong>dir1</strong>/%{REQUEST_URI} -f
382 RewriteRule ^(.+) %{DOCUMENT_ROOT}/<strong>dir1</strong>/$1 [L]
384 # second try to find it in dir2/...
385 # ...and if found stop and be happy:
386 RewriteCond %{DOCUMENT_ROOT}/<strong>dir2</strong>/%{REQUEST_URI} -f
387 RewriteRule ^(.+) %{DOCUMENT_ROOT}/<strong>dir2</strong>/$1 [L]
389 # else go on for other Alias or ScriptAlias directives,
398 <section id="archive-access-multiplexer">
400 <title>Redirecting to Geographically Distributed Servers</title>
403 <dt>Description:</dt>
406 <p>We have numerous mirrors of our website, and want to redirect
407 people to the one that is located in the country where they are
414 <p>Looking at the hostname of the requesting client, we determine
415 which country they are coming from. If we can't do a lookup on their
416 IP address, we fall back to a default server.</p>
417 <p>We'll use a <directive module="mod_rewrite">RewriteMap</directive>
418 directive to build a list of servers that we wish to use.</p>
420 <highlight language="config">
423 RewriteMap multiplex txt:/path/to/map.mirrors
424 RewriteCond %{REMOTE_HOST} ([a-z]+)$ [NC]
425 RewriteRule ^/(.*)$ ${multiplex:<strong>%1</strong>|http://www.example.com/}$1 [R,L]
429 ## map.mirrors -- Multiplexing Map<br />
431 de http://www.example.de/<br />
432 uk http://www.example.uk/<br />
433 com http://www.example.com/<br />
440 <note type="warning">This ruleset relies on
441 <directive module="core">HostNameLookups</directive>
442 being set <code>on</code>, which can be
443 a significant performance hit.</note>
445 <p>The <directive module="mod_rewrite">RewriteCond</directive>
446 directive captures the last portion of the hostname of the
447 requesting client - the country code - and the following RewriteRule
448 uses that value to look up the appropriate mirror host in the map
455 <section id="canonicalurl">
457 <title>Canonical URLs</title>
460 <dt>Description:</dt>
463 <p>On some webservers there is more than one URL for a
464 resource. Usually there are canonical URLs (which are be
465 actually used and distributed) and those which are just
466 shortcuts, internal ones, and so on. Independent of which URL the
467 user supplied with the request, they should finally see the
468 canonical one in their browser address bar.</p>
474 <p>We do an external HTTP redirect for all non-canonical
475 URLs to fix them in the location view of the Browser and
476 for all subsequent requests. In the example ruleset below
477 we replace <code>/puppies</code> and <code>/canines</code>
478 by the canonical <code>/dogs</code>.</p>
480 <highlight language="config">RewriteRule ^/(puppies|canines)/(.*) /dogs/$2 [R]</highlight>
485 This should really be accomplished with Redirect or RedirectMatch
488 <highlight language="config">
489 RedirectMatch "^/(puppies|canines)/(.*)" "/dogs/$2"
496 <section id="moveddocroot">
498 <title>Moved <code>DocumentRoot</code></title>
501 <dt>Description:</dt>
504 <p>Usually the <directive module="core">DocumentRoot</directive>
505 of the webserver directly relates to the URL "<code>/</code>".
506 But often this data is not really of top-level priority. For example,
507 you may wish for visitors, on first entering a site, to go to a
508 particular subdirectory <code>/about/</code>. This may be accomplished
509 using the following ruleset:</p>
515 <p>We redirect the URL <code>/</code> to
516 <code>/about/</code>:
519 <highlight language="config">
521 RewriteRule ^/$ /about/ [<strong>R</strong>]
524 <p>Note that this can also be handled using the <directive
525 module="mod_alias">RedirectMatch</directive> directive:</p>
527 <highlight language="config">
528 RedirectMatch "^/$" "http://example.com/about/"
531 <p>Note also that the example rewrites only the root URL. That is, it
532 rewrites a request for <code>http://example.com/</code>, but not a
533 request for <code>http://example.com/page.html</code>. If you have in
534 fact changed your document root - that is, if <strong>all</strong> of
535 your content is in fact in that subdirectory, it is greatly preferable
536 to simply change your <directive module="core">DocumentRoot</directive>
537 directive, or move all of the content up one directory,
538 rather than rewriting URLs.</p>
544 <section id="fallback-resource">
545 <title>Fallback Resource</title>
548 <dt>Description:</dt>
549 <dd>You want a single resource (say, a certain file, like index.php) to
550 handle all requests that come to a particular directory, except those
551 that should go to an existing resource such as an image, or a css file.</dd>
555 <p>As of version 2.2.16, you should use the <directive
556 module="mod_dir">FallbackResource</directive> directive for this:</p>
558 <highlight language="config">
559 <Directory "/var/www/my_blog">
560 FallbackResource index.php
564 <p>However, in earlier versions of Apache, or if your needs are more
565 complicated than this, you can use a variation of the following rewrite
566 set to accomplish the same thing:</p>
568 <highlight language="config">
569 <Directory "/var/www/my_blog">
572 RewriteCond /var/www/my_blog/%{REQUEST_FILENAME} !-f
573 RewriteCond /var/www/my_blog/%{REQUEST_FILENAME} !-d
574 RewriteRule ^ index.php [PT]
578 <p>If, on the other hand, you wish to pass the requested URI as a query
579 string argument to index.php, you can replace that RewriteRule with:</p>
581 <highlight language="config">
582 RewriteRule (.*) index.php?$1 [PT,QSA]
585 <p>Note that these rulesets can be used in a <code>.htaccess</code>
586 file, as well as in a <Directory> block.</p>
594 <section id="rewrite-query">
595 <title>Rewrite query string</title>
598 <dt>Description:</dt>
599 <dd>You want to capture a particular value from a query string
600 and either replace it or incorporate it into another component
605 <p> Many of the solutions in this section will all use the same condition,
606 which leaves the matched value in the %2 backreference. %1 is the beginining
607 of the query string (up to the key of intererest), and %3 is the remainder. This
608 condition is a bit complex for flexibility and to avoid double '&&' in the
611 <li>This solution removes the matching key and value:
613 <highlight language="config">
615 RewriteCond %{QUERY_STRING} (.*(?:^|&))mykey=([^&]*)&?(.*)&?$
616 RewriteRule (.*) $1?%1%3
620 <li>This solution uses the captured value in the URL subsitution,
621 discarding the rest of the original query by appending a '?':
623 <highlight language="config">
624 # Copy from query string to PATH_INFO
625 RewriteCond %{QUERY_STRING} (.*(?:^|&))mykey=([^&]*)&?(.*)&?$
626 RewriteRule (.*) $1/products/%2/? [PT]
630 <li>This solution checks the captured value in a subsequent condition:
632 <highlight language="config">
633 # Capture the value of mykey in the query string
634 RewriteCond %{QUERY_STRING} (.*(?:^|&))mykey=([^&]*)&?(.*)&?$
635 RewriteCond %2 !=not-so-secret-value
636 RewriteRule (.*) - [F]
640 <li>This solution shows the reverse of the previous ones, copying
641 path components (perhaps PATH_INFO) from the URL into the query string.
642 <highlight language="config">
643 # The desired URL might be /products/kitchen-sink, and the script expects
644 # /path?products=kitchen-sink.
645 RewriteRule ^/?path/([^/]+)/([^/]+) /path?$1=$2 [PT]