]> granicus.if.org Git - apache/blob - docs/manual/rewrite/remapping.xml
Minor tweak: Rename links to 'Using RewriteMap' rather than 'RewriteMap'.
[apache] / docs / manual / rewrite / remapping.xml
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$ -->
5
6 <!--
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
13
14      http://www.apache.org/licenses/LICENSE-2.0
15
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.
21 -->
22
23 <manualpage metafile="remapping.xml.meta">
24   <parentdocument href="./">Rewrite</parentdocument>
25
26 <title>Redirecting and Remapping with mod_rewrite</title>
27
28 <summary>
29
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>
35
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
39 configuration.</note>
40
41 </summary>
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 and tricks</a></seealso>
50 <seealso><a href="avoid.html">When not to use mod_rewrite</a></seealso>
51
52 <section id="old-to-new">
53
54   <title>From Old to New (internal)</title>
55
56   <dl>
57     <dt>Description:</dt>
58
59     <dd>
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>
66     </dd>
67
68     <dt>Solution:</dt>
69
70     <dd>
71       <p>We rewrite the old URL to the new one internally via the
72       following rule:</p>
73
74 <example><pre>
75 RewriteEngine  on
76 RewriteRule    ^<strong>/old</strong>\.html$  <strong>/new</strong>.html [PT]
77 </pre></example>
78     </dd>
79   </dl>
80
81 </section>
82
83 <section id="old-to-new-extern">
84
85   <title>Rewriting From Old to New (external)</title>
86
87   <dl>
88     <dt>Description:</dt>
89
90     <dd>
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
96       change, too.</p>
97     </dd>
98
99     <dt>Solution:</dt>
100
101     <dd>
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>
104
105 <example><pre>
106 RewriteEngine  on
107 RewriteRule    ^<strong>/foo</strong>\.html$  <strong>bar</strong>.html  [<strong>R</strong>]
108 </pre></example>
109 </dd>
110
111 <dt>Discussion</dt>
112
113     <dd>
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>
118
119     <example>
120     Redirect /foo.html /bar.html
121     </example>
122
123     </dd>
124   </dl>
125
126 </section>
127
128 <section id="movehomedirs">
129
130   <title>Resource Moved to Another Server</title>
131
132   <dl>
133     <dt>Description:</dt>
134
135     <dd>
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>
139     </dd>
140
141     <dt>Solution:</dt>
142
143     <dd>
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>
147
148 <example><title>With mod_rewrite</title><pre>
149 RewriteEngine on
150 RewriteRule   ^/docs/(.+)  http://new.example.com/docs/$1  [R,L]
151 </pre></example>
152
153 <example><title>With RedirectMatch</title><pre>
154 RedirectMatch ^/docs/(.*) http://new.example.com/docs/$1
155 </pre></example>
156
157 <example><title>With Redirect</title><pre>
158 Redirect /docs/ http://new.example.com/docs/
159 </pre></example>
160     </dd>
161   </dl>
162
163 </section>
164
165 <section id="static-to-dynamic">
166
167   <title>From Static to Dynamic</title>
168
169   <dl>
170     <dt>Description:</dt>
171
172     <dd>
173       <p>How can we transform a static page
174       <code>foo.html</code> into a dynamic variant
175       <code>foo.cgi</code> in a seamless way, i.e. without notice
176       by the browser/user.</p>
177     </dd>
178
179     <dt>Solution:</dt>
180
181     <dd>
182       <p>We just rewrite the URL to the CGI-script and force the
183       handler to be <strong>cgi-script</strong> so that it is
184       executed as a CGI program.
185       This way a request to <code>/~quux/foo.html</code>
186       internally leads to the invocation of
187       <code>/~quux/foo.cgi</code>.</p>
188
189 <example><pre>
190 RewriteEngine  on
191 RewriteBase    /~quux/
192 RewriteRule    ^foo\.<strong>html</strong>$  foo.<strong>cgi</strong>  [H=<strong>cgi-script</strong>]
193 </pre></example>
194     </dd>
195   </dl>
196
197 </section>
198
199 <section id="backward-compatibility">
200
201   <title>Backward Compatibility for file extension change</title>
202
203   <dl>
204     <dt>Description:</dt>
205
206     <dd>
207       <p>How can we make URLs backward compatible (still
208       existing virtually) after migrating <code>document.YYYY</code>
209       to <code>document.XXXX</code>, e.g. after translating a
210       bunch of <code>.html</code> files to <code>.php</code>?</p>
211     </dd>
212
213     <dt>Solution:</dt>
214
215     <dd>
216       <p>We rewrite the name to its basename and test for
217       existence of the new extension. If it exists, we take
218       that name, else we rewrite the URL to its original state.</p>
219
220 <example><pre>
221 #   backward compatibility ruleset for
222 #   rewriting document.html to document.php
223 #   when and only when document.php exists
224 &lt;Directory /var/www/htdocs&gt;
225 RewriteEngine on
226 RewriteBase /var/www/htdocs
227
228 RewriteCond $1.php -f
229 RewriteCond $1.html !-f
230 RewriteRule ^(.*).html$ $1.php
231 &lt;/Directory&gt;
232 </pre></example>
233     </dd>
234
235     <dt>Discussion</dt>
236     <dd>
237     <p>This example uses an often-overlooked feature of mod_rewrite,
238     by taking advantage of the order of execution of the ruleset. In
239     particular, mod_rewrite evaluates the left-hand-side of the
240     RewriteRule before it evaluates the RewriteCond directives.
241     Consequently, $1 is already defined by the time the RewriteCond
242     directives are evaluated. This allows us to test for the existence
243     of the original (<code>document.html</code>) and target
244     (<code>document.php</code>) files using the same base filename.</p>
245
246     <p>This ruleset is designed to use in a per-directory context (In a
247     &lt;Directory&gt; block or in a .htaccess file), so that the
248     <code>-f</code> checks are looking at the correct directory path.
249     You may need to set a <directive
250     module="mod_rewite">RewriteBase</directive> directive to specify the
251     directory base that you're working in.</p>
252     </dd>
253   </dl>
254
255 </section>
256
257 <section id="canonicalhost">
258
259 <title>Canonical Hostnames</title>
260
261       <dl>
262         <dt>Description:</dt>
263
264         <dd>The goal of this rule is to force the use of a particular
265         hostname, in preference to other hostnames which may be used to
266         reach the same site. For example, if you wish to force the use
267         of <strong>www.example.com</strong> instead of
268         <strong>example.com</strong>, you might use a variant of the
269         following recipe.</dd>
270
271         <dt>Solution:</dt>
272
273         <dd>
274
275 <p>The very best way to solve this doesn't involve mod_rewrite at all,
276 but rather uses the <directive module="alias">Redirect</directive>
277 directive placed in a virtual host for the non-canonical
278 hostname(s).</p>
279
280 <example><pre>
281 &lt;VirtualHost *:80&gt;
282   ServerName undesired.example.com
283   ServerAlias example.com notthis.example.com
284
285   Redirect / http://www.example.com/
286 &lt;/VirtualHost&gt;
287 </pre></example>
288
289 <p>However, there are situations where you'll need to use mod_rewrite -
290 primarily when you don't have access to the main server configuration
291 file, or if you wish to do this dynamically for a larger number of
292 hostnames. For these situations, you might use one of the recipes
293 below.</p>
294
295 <p>For sites running on a port other than 80:</p>
296 <example><pre>
297 RewriteCond %{HTTP_HOST}   !^www\.example\.com [NC]
298 RewriteCond %{HTTP_HOST}   !^$
299 RewriteCond %{SERVER_PORT} !^80$
300 RewriteRule ^/?(.*)         http://www.example.com:%{SERVER_PORT}/$1 [L,R,NE]
301 </pre></example>
302
303 <p>And for a site running on port 80</p>
304 <example><pre>
305 RewriteCond %{HTTP_HOST}   !^www\.example\.com [NC]
306 RewriteCond %{HTTP_HOST}   !^$
307 RewriteRule ^/?(.*)         http://www.example.com/$1 [L,R,NE]
308 </pre></example>
309
310         <p>
311         If you wanted to do this generically for all domain names - that
312         is, if you want to redirect <strong>example.com</strong> to
313         <strong>www.example.com</strong> for all possible values of
314         <strong>example.com</strong>, you could use the following
315         recipe:</p>
316
317 <example><pre>
318 RewriteCond %{HTTP_HOST} !^www\. [NC]
319 RewriteCond %{HTTP_HOST} !^$
320 RewriteRule ^/?(.*) http://www.%{HTTP_HOST}/$1 [L,R,NE]
321 </pre></example>
322
323     <p>These rulesets will work either in your main server configuration
324     file, or in a <code>.htaccess</code> file placed in the <directive
325     module="core">DocumentRoot</directive> of the server.</p>
326         </dd>
327       </dl>
328
329 </section>
330
331 <section id="multipledirs">
332
333   <title>Search for pages in more than one directory</title>
334
335   <dl>
336     <dt>Description:</dt>
337
338     <dd>
339       <p>A particular resource might exist in one of several places, and
340       we want to look in those places for the resource when it is
341       requested. Perhaps we've recently rearranged our directory
342       structure, dividing content into several locations.</p>
343     </dd>
344
345     <dt>Solution:</dt>
346
347     <dd>
348       <p>The following ruleset searches in two directories to find the
349       resource, and, if not finding it in either place, will attempt to
350       just serve it out of the location requested.</p>
351
352 <example><pre>
353 RewriteEngine on
354
355 #   first try to find it in dir1/...
356 #   ...and if found stop and be happy:
357 RewriteCond         %{DOCUMENT_ROOT}/<strong>dir1</strong>/%{REQUEST_URI}  -f
358 RewriteRule  ^(.+)  %{DOCUMENT_ROOT}/<strong>dir1</strong>/$1  [L]
359
360 #   second try to find it in dir2/...
361 #   ...and if found stop and be happy:
362 RewriteCond         %{DOCUMENT_ROOT}/<strong>dir2</strong>/%{REQUEST_URI}  -f
363 RewriteRule  ^(.+)  %{DOCUMENT_ROOT}/<strong>dir2</strong>/$1  [L]
364
365 #   else go on for other Alias or ScriptAlias directives,
366 #   etc.
367 RewriteRule   ^  -  [PT]
368 </pre></example>
369     </dd>
370   </dl>
371
372 </section>
373
374 <section id="archive-access-multiplexer">
375
376   <title>Redirecting to Geographically Distributed Servers</title>
377
378   <dl>
379     <dt>Description:</dt>
380
381     <dd>
382     <p>We have numerous mirrors of our website, and want to redirect
383     people to the one that is located in the country where they are
384     located.</p>
385     </dd>
386
387     <dt>Solution:</dt>
388
389     <dd>
390     <p>Looking at the hostname of the requesting client, we determine
391     which country they are coming from. If we can't do a lookup on their
392     IP address, we fall back to a default server.</p>
393     <p>We'll use a <directive module="mod_rewrite">RewriteMap</directive>
394     directive to build a list of servers that we wish to use.</p>
395
396 <example><pre>
397 HostnameLookups on
398 RewriteEngine on
399 RewriteMap    multiplex         txt:/path/to/map.mirrors
400 RewriteCond  %{REMOTE_HOST}     ([a-z]+)$ [NC]
401 RewriteRule   ^/(.*)$  ${multiplex:<strong>%1</strong>|http://www.example.com/}$1  [R,L]
402 </pre></example>
403
404 <example><pre>
405 ##  map.mirrors -- Multiplexing Map
406
407 de        http://www.example.de/
408 uk        http://www.example.uk/
409 com       http://www.example.com/
410 ##EOF##
411 </pre></example>
412     </dd>
413
414     <dt>Discussion</dt>
415     <dd>
416     <note type="warning">This ruleset relies on 
417     <directive module="core">HostNameLookups</directive> 
418     being set <code>on</code>, which can be
419     a significant performance hit.</note>
420
421     <p>The <directive module="mod_rewrite">RewriteCond</directive>
422     directive captures the last portion of the hostname of the
423     requesting client - the country code - and the following RewriteRule
424     uses that value to look up the appropriate mirror host in the map
425     file.</p>
426     </dd>
427   </dl>
428
429 </section>
430
431 <section id="browser-dependent-content">
432
433   <title>Browser Dependent Content</title>
434
435   <dl>
436     <dt>Description:</dt>
437
438     <dd>
439       <p>We wish to provide different content based on the browser, or
440       user-agent, which is requesting the content.</p>
441     </dd>
442
443     <dt>Solution:</dt>
444
445     <dd>
446       <p>We have to decide, based on the HTTP header "User-Agent",
447       which content to serve. The following config
448       does the following: If the HTTP header "User-Agent"
449       contains "Mozilla/3", the page <code>foo.html</code>
450       is rewritten to <code>foo.NS.html</code> and the
451       rewriting stops. If the browser is "Lynx" or "Mozilla" of
452       version 1 or 2, the URL becomes <code>foo.20.html</code>.
453       All other browsers receive page <code>foo.32.html</code>.
454       This is done with the following ruleset:</p>
455
456 <example><pre>
457 RewriteCond %{HTTP_USER_AGENT}  ^<strong>Mozilla/3</strong>.*
458 RewriteRule ^foo\.html$         foo.<strong>NS</strong>.html          [<strong>L</strong>]
459
460 RewriteCond %{HTTP_USER_AGENT}  ^<strong>Lynx/</strong>.*         [OR]
461 RewriteCond %{HTTP_USER_AGENT}  ^<strong>Mozilla/[12]</strong>.*
462 RewriteRule ^foo\.html$         foo.<strong>20</strong>.html          [<strong>L</strong>]
463
464 RewriteRule ^foo\.html$         foo.<strong>32</strong>.html          [<strong>L</strong>]
465 </pre></example>
466     </dd>
467   </dl>
468
469 </section>
470
471 <section id="canonicalurl">
472
473 <title>Canonical URLs</title>
474
475 <dl>
476  <dt>Description:</dt>
477
478    <dd>
479      <p>On some webservers there is more than one URL for a
480      resource. Usually there are canonical URLs (which are be
481      actually used and distributed) and those which are just
482      shortcuts, internal ones, and so on. Independent of which URL the
483      user supplied with the request, they should finally see the
484      canonical one in their browser address bar.</p>
485    </dd>
486
487    <dt>Solution:</dt>
488
489      <dd>
490        <p>We do an external HTTP redirect for all non-canonical
491        URLs to fix them in the location view of the Browser and
492        for all subsequent requests. In the example ruleset below
493        we replace <code>/puppies</code> and <code>/canines</code>
494        by the canonical <code>/dogs</code>.</p>
495
496 <example><pre>
497 RewriteRule   ^/(puppies|canines)/(.*)    /dogs/$2  [R]
498 </pre></example>
499         </dd>
500
501      <dt>Discussion:</dt>
502      <dd>
503      This should really be accomplished with Redirect or RedirectMatch
504      directives:
505
506      <example><pre>
507      RedirectMatch ^/(puppies|canines)/(.*) /dogs/$2
508      </pre></example>
509      </dd>
510       </dl>
511
512 </section>
513
514 <section id="moveddocroot">
515
516   <title>Moved <code>DocumentRoot</code></title>
517
518   <dl>
519     <dt>Description:</dt>
520
521     <dd>
522 <p>Usually the <directive module="core">DocumentRoot</directive>
523 of the webserver directly relates to the URL "<code>/</code>".
524 But often this data is not really of top-level priority. For example,
525 you may wish for visitors, on first entering a site, to go to a
526 particular subdirectory <code>/about/</code>. This may be accomplished
527 using the following ruleset:</p>
528 </dd>
529
530     <dt>Solution:</dt>
531
532     <dd>
533       <p>We redirect the URL <code>/</code> to
534       <code>/about/</code>:
535       </p>
536      
537 <example><pre>
538 RewriteEngine on
539 RewriteRule   <strong>^/$</strong>  /about/  [<strong>R</strong>]
540 </pre></example>
541
542 <p>Note that this can also be handled using the <directive
543 module="mod_alias">RedirectMatch</directive> directive:</p>
544
545 <example>
546 RedirectMatch ^/$ http://example.com/about/
547 </example>
548
549 <p>Note also that the example rewrites only the root URL. That is, it
550 rewrites a request for <code>http://example.com/</code>, but not a
551 request for <code>http://example.com/page.html</code>. If you have in 
552 fact changed your document root - that is, if <strong>all</strong> of 
553 your content is in fact in that subdirectory, it is greatly preferable 
554 to simply change your <directive module="core">DocumentRoot</directive>
555 directive, or move all of the content up one directory,
556 rather than rewriting URLs.</p>
557 </dd>
558 </dl>
559
560 </section>
561
562 <section id="fallback-resource">
563 <title>Fallback Resource</title>
564
565 <dl>
566 <dt>Description:</dt>
567 <dd>You want a single resource (say, a certain file, like index.php) to
568 handle all requests that come to a particular directory, except those
569 that should go to an existing resource such as an image, or a css file.</dd>
570
571 <dt>Solution:</dt>
572 <dd>
573 <p>As of version 2.4, you should use the <directive
574 module="mod_dir">FallbackResource</directive> directive for this:</p>
575
576 <example>
577 <pre>
578 &lt;Directory /var/www/my_blog&gt;
579   FallbackResource index.php
580 &lt;/Directory&gt;
581 </pre>
582 </example>
583
584 <p>However, in earlier versions of Apache, or if your needs are more
585 complicated than this, you can use a variation of the following rewrite
586 set to accomplish the same thing:</p>
587
588 <example>
589 <pre>
590 &lt;Directory /var/www/my_blog&gt;
591   RewriteBase /my_blog
592
593   RewriteCond /var/www/my_blog/%{REQUEST_FILENAME} !-f
594   RewriteCond /var/www/my_blog/%{REQUEST_FILENAME} !-d
595   RewriteRule ^ index.php [PT]
596 &lt;/Directory&gt;
597 </pre>
598 </example>
599
600 <p>If, on the other hand, you wish to pass the requested URI as a query
601 string argument to index.php, you can replace that RewriteRule with:</p>
602
603 <example>
604 <pre>
605   RewriteRule (.*) index.php?$1 [PT,QSA]
606 </pre>
607 </example>
608
609 <p>Note that these rulesets can be uses in a <code>.htaccess</code>
610 file, as well as in a &lt;Directory&gt; block.</p>
611
612 </dd>
613
614 </dl>
615
616 </section>
617
618 </manualpage>