]> granicus.if.org Git - apache/blob - docs/manual/rewrite/remapping.xml
Updates one of the "advanced" recipes and rewrites description.
[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</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>
75 RewriteEngine  on<br />
76 RewriteRule    ^<strong>/old</strong>\.html$  <strong>/new</strong>.html [PT]
77 </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>
106 RewriteEngine  on<br />
107 RewriteRule    ^<strong>/foo</strong>\.html$  <strong>bar</strong>.html  [<strong>R</strong>]
108 </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>
149 RewriteEngine on<br />
150 RewriteRule   ^/docs/(.+)  http://new.example.com/docs/$1  [R,L]
151 </example>
152
153 <example><title>With RedirectMatch</title>
154 RedirectMatch ^/docs/(.*) http://new.example.com/docs/$1
155 </example>
156
157 <example><title>With Redirect</title>
158 Redirect /docs/ http://new.example.com/docs/
159 </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>
190 RewriteEngine  on<br />
191 RewriteBase    /~quux/<br />
192 RewriteRule    ^foo\.<strong>html</strong>$  foo.<strong>cgi</strong>  [H=<strong>cgi-script</strong>]
193 </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>
221 #   backward compatibility ruleset for<br />
222 #   rewriting document.html to document.php<br />
223 #   when and only when document.php exists<br />
224 &lt;Directory /var/www/htdocs&gt;<br />
225 <indent>
226 RewriteEngine on<br />
227 RewriteBase /var/www/htdocs<br />
228 <br />
229 RewriteCond $1.php -f<br />
230 RewriteCond $1.html !-f<br />
231 RewriteRule ^(.*).html$ $1.php<br />
232 </indent>
233 &lt;/Directory&gt;
234 </example>
235     </dd>
236
237     <dt>Discussion</dt>
238     <dd>
239     <p>This example uses an often-overlooked feature of mod_rewrite,
240     by taking advantage of the order of execution of the ruleset. In
241     particular, mod_rewrite evaluates the left-hand-side of the
242     RewriteRule before it evaluates the RewriteCond directives.
243     Consequently, $1 is already defined by the time the RewriteCond
244     directives are evaluated. This allows us to test for the existence
245     of the original (<code>document.html</code>) and target
246     (<code>document.php</code>) files using the same base filename.</p>
247
248     <p>This ruleset is designed to use in a per-directory context (In a
249     &lt;Directory&gt; block or in a .htaccess file), so that the
250     <code>-f</code> checks are looking at the correct directory path.
251     You may need to set a <directive
252     module="mod_rewite">RewriteBase</directive> directive to specify the
253     directory base that you're working in.</p>
254     </dd>
255   </dl>
256
257 </section>
258
259 <section id="canonicalhost">
260
261 <title>Canonical Hostnames</title>
262
263       <dl>
264         <dt>Description:</dt>
265
266         <dd>The goal of this rule is to force the use of a particular
267         hostname, in preference to other hostnames which may be used to
268         reach the same site. For example, if you wish to force the use
269         of <strong>www.example.com</strong> instead of
270         <strong>example.com</strong>, you might use a variant of the
271         following recipe.</dd>
272
273         <dt>Solution:</dt>
274
275         <dd>
276
277 <p>The very best way to solve this doesn't involve mod_rewrite at all,
278 but rather uses the <directive module="alias">Redirect</directive>
279 directive placed in a virtual host for the non-canonical
280 hostname(s).</p>
281
282 <example>
283 &lt;VirtualHost *:80&gt;<br />
284 <indent>
285   ServerName undesired.example.com<br />
286   ServerAlias example.com notthis.example.com<br />
287 <br />
288   Redirect / http://www.example.com/<br />
289 </indent>
290 &lt;/VirtualHost&gt;<br />
291 <br />
292 &lt;VirtualHost *:80&gt;<br />
293 <indent>
294   ServerName www.example.com<br />
295 </indent>
296 &lt;/VirtualHost&gt;
297 </example>
298
299 <p>You can alternatively accomplish this using the 
300 <directive module="core" type="section">If</directive>
301 directive:</p>
302
303 <example>
304 &lt;If "%{HTTP_HOST} != 'www.example.com'"&gt;<br />
305 <indent>
306 Redirect / http://www.example.com/
307 </indent>
308 &lt;/If&gt;
309 </example>
310
311 <p>Or, for example, to redirect a portion of your site to HTTPS, you
312 might do the following:</p>
313
314 <example>
315 &lt;If "%{SERVER_PROTOCOL} != 'HTTPS'"&gt;<br />
316 <indent>
317 Redirect /admin/ https://www.example.com/admin/
318 </indent>
319 &lt;/If&gt;
320 </example>
321
322 <p>If, for whatever reason, you still want to use <code>mod_rewrite</code>
323 - if, for example, you need this to work with a larger set of RewriteRules - 
324 you might use one of the recipes below.</p>
325
326 <p>For sites running on a port other than 80:</p>
327 <example>
328 RewriteCond %{HTTP_HOST}   !^www\.example\.com [NC]<br />
329 RewriteCond %{HTTP_HOST}   !^$<br />
330 RewriteCond %{SERVER_PORT} !^80$<br />
331 RewriteRule ^/?(.*)         http://www.example.com:%{SERVER_PORT}/$1 [L,R,NE]
332 </example>
333
334 <p>And for a site running on port 80</p>
335 <example>
336 RewriteCond %{HTTP_HOST}   !^www\.example\.com [NC]<br />
337 RewriteCond %{HTTP_HOST}   !^$<br />
338 RewriteRule ^/?(.*)         http://www.example.com/$1 [L,R,NE]
339 </example>
340
341         <p>
342         If you wanted to do this generically for all domain names - that
343         is, if you want to redirect <strong>example.com</strong> to
344         <strong>www.example.com</strong> for all possible values of
345         <strong>example.com</strong>, you could use the following
346         recipe:</p>
347
348 <example>
349 RewriteCond %{HTTP_HOST} !^www\. [NC]<br />
350 RewriteCond %{HTTP_HOST} !^$<br />
351 RewriteRule ^/?(.*) http://www.%{HTTP_HOST}/$1 [L,R,NE]
352 </example>
353
354     <p>These rulesets will work either in your main server configuration
355     file, or in a <code>.htaccess</code> file placed in the <directive
356     module="core">DocumentRoot</directive> of the server.</p>
357         </dd>
358       </dl>
359
360 </section>
361
362 <section id="multipledirs">
363
364   <title>Search for pages in more than one directory</title>
365
366   <dl>
367     <dt>Description:</dt>
368
369     <dd>
370       <p>A particular resource might exist in one of several places, and
371       we want to look in those places for the resource when it is
372       requested. Perhaps we've recently rearranged our directory
373       structure, dividing content into several locations.</p>
374     </dd>
375
376     <dt>Solution:</dt>
377
378     <dd>
379       <p>The following ruleset searches in two directories to find the
380       resource, and, if not finding it in either place, will attempt to
381       just serve it out of the location requested.</p>
382
383 <example>
384 RewriteEngine on<br />
385 <br />
386 #   first try to find it in dir1/...<br />
387 #   ...and if found stop and be happy:<br />
388 RewriteCond         %{DOCUMENT_ROOT}/<strong>dir1</strong>/%{REQUEST_URI}  -f<br />
389 RewriteRule  ^(.+)  %{DOCUMENT_ROOT}/<strong>dir1</strong>/$1  [L]<br />
390 <br />
391 #   second try to find it in dir2/...<br />
392 #   ...and if found stop and be happy:<br />
393 RewriteCond         %{DOCUMENT_ROOT}/<strong>dir2</strong>/%{REQUEST_URI}  -f<br />
394 RewriteRule  ^(.+)  %{DOCUMENT_ROOT}/<strong>dir2</strong>/$1  [L]<br />
395 <br />
396 #   else go on for other Alias or ScriptAlias directives,<br />
397 #   etc.<br />
398 RewriteRule   ^  -  [PT]
399 </example>
400     </dd>
401   </dl>
402
403 </section>
404
405 <section id="archive-access-multiplexer">
406
407   <title>Redirecting to Geographically Distributed Servers</title>
408
409   <dl>
410     <dt>Description:</dt>
411
412     <dd>
413     <p>We have numerous mirrors of our website, and want to redirect
414     people to the one that is located in the country where they are
415     located.</p>
416     </dd>
417
418     <dt>Solution:</dt>
419
420     <dd>
421     <p>Looking at the hostname of the requesting client, we determine
422     which country they are coming from. If we can't do a lookup on their
423     IP address, we fall back to a default server.</p>
424     <p>We'll use a <directive module="mod_rewrite">RewriteMap</directive>
425     directive to build a list of servers that we wish to use.</p>
426
427 <example>
428 HostnameLookups on<br />
429 RewriteEngine on<br />
430 RewriteMap    multiplex         txt:/path/to/map.mirrors<br />
431 RewriteCond  %{REMOTE_HOST}     ([a-z]+)$ [NC]<br />
432 RewriteRule   ^/(.*)$  ${multiplex:<strong>%1</strong>|http://www.example.com/}$1  [R,L]
433 </example>
434
435 <example>
436 ##  map.mirrors -- Multiplexing Map<br />
437 <br />
438 de        http://www.example.de/<br />
439 uk        http://www.example.uk/<br />
440 com       http://www.example.com/<br />
441 ##EOF##
442 </example>
443     </dd>
444
445     <dt>Discussion</dt>
446     <dd>
447     <note type="warning">This ruleset relies on 
448     <directive module="core">HostNameLookups</directive> 
449     being set <code>on</code>, which can be
450     a significant performance hit.</note>
451
452     <p>The <directive module="mod_rewrite">RewriteCond</directive>
453     directive captures the last portion of the hostname of the
454     requesting client - the country code - and the following RewriteRule
455     uses that value to look up the appropriate mirror host in the map
456     file.</p>
457     </dd>
458   </dl>
459
460 </section>
461
462 <section id="browser-dependent-content">
463
464   <title>Browser Dependent Content</title>
465
466   <dl>
467     <dt>Description:</dt>
468
469     <dd>
470       <p>We wish to provide different content based on the browser, or
471       user-agent, which is requesting the content.</p>
472     </dd>
473
474     <dt>Solution:</dt>
475
476     <dd>
477       <p>We have to decide, based on the HTTP header "User-Agent",
478       which content to serve. The following config
479       does the following: If the HTTP header "User-Agent"
480       contains "Mozilla/3", the page <code>foo.html</code>
481       is rewritten to <code>foo.NS.html</code> and the
482       rewriting stops. If the browser is "Lynx" or "Mozilla" of
483       version 1 or 2, the URL becomes <code>foo.20.html</code>.
484       All other browsers receive page <code>foo.32.html</code>.
485       This is done with the following ruleset:</p>
486
487 <example>
488 RewriteCond %{HTTP_USER_AGENT}  ^<strong>Mozilla/3</strong>.*<br />
489 RewriteRule ^foo\.html$         foo.<strong>NS</strong>.html          [<strong>L</strong>]<br />
490 <br />
491 RewriteCond %{HTTP_USER_AGENT}  ^<strong>Lynx/</strong>         [OR]<br />
492 RewriteCond %{HTTP_USER_AGENT}  ^<strong>Mozilla/[12]</strong><br />
493 RewriteRule ^foo\.html$         foo.<strong>20</strong>.html          [<strong>L</strong>]<br />
494 <br />
495 RewriteRule ^foo\.html$         foo.<strong>32</strong>.html          [<strong>L</strong>]
496 </example>
497     </dd>
498   </dl>
499
500 </section>
501
502 <section id="canonicalurl">
503
504 <title>Canonical URLs</title>
505
506 <dl>
507  <dt>Description:</dt>
508
509    <dd>
510      <p>On some webservers there is more than one URL for a
511      resource. Usually there are canonical URLs (which are be
512      actually used and distributed) and those which are just
513      shortcuts, internal ones, and so on. Independent of which URL the
514      user supplied with the request, they should finally see the
515      canonical one in their browser address bar.</p>
516    </dd>
517
518    <dt>Solution:</dt>
519
520      <dd>
521        <p>We do an external HTTP redirect for all non-canonical
522        URLs to fix them in the location view of the Browser and
523        for all subsequent requests. In the example ruleset below
524        we replace <code>/puppies</code> and <code>/canines</code>
525        by the canonical <code>/dogs</code>.</p>
526
527 <example>
528 RewriteRule   ^/(puppies|canines)/(.*)    /dogs/$2  [R]
529 </example>
530         </dd>
531
532      <dt>Discussion:</dt>
533      <dd>
534      This should really be accomplished with Redirect or RedirectMatch
535      directives:
536
537      <example>
538      RedirectMatch ^/(puppies|canines)/(.*) /dogs/$2
539      </example>
540      </dd>
541       </dl>
542
543 </section>
544
545 <section id="moveddocroot">
546
547   <title>Moved <code>DocumentRoot</code></title>
548
549   <dl>
550     <dt>Description:</dt>
551
552     <dd>
553 <p>Usually the <directive module="core">DocumentRoot</directive>
554 of the webserver directly relates to the URL "<code>/</code>".
555 But often this data is not really of top-level priority. For example,
556 you may wish for visitors, on first entering a site, to go to a
557 particular subdirectory <code>/about/</code>. This may be accomplished
558 using the following ruleset:</p>
559 </dd>
560
561     <dt>Solution:</dt>
562
563     <dd>
564       <p>We redirect the URL <code>/</code> to
565       <code>/about/</code>:
566       </p>
567      
568 <example>
569 RewriteEngine on<br />
570 RewriteRule   <strong>^/$</strong>  /about/  [<strong>R</strong>]
571 </example>
572
573 <p>Note that this can also be handled using the <directive
574 module="mod_alias">RedirectMatch</directive> directive:</p>
575
576 <example>
577 RedirectMatch ^/$ http://example.com/about/
578 </example>
579
580 <p>Note also that the example rewrites only the root URL. That is, it
581 rewrites a request for <code>http://example.com/</code>, but not a
582 request for <code>http://example.com/page.html</code>. If you have in 
583 fact changed your document root - that is, if <strong>all</strong> of 
584 your content is in fact in that subdirectory, it is greatly preferable 
585 to simply change your <directive module="core">DocumentRoot</directive>
586 directive, or move all of the content up one directory,
587 rather than rewriting URLs.</p>
588 </dd>
589 </dl>
590
591 </section>
592
593 <section id="fallback-resource">
594 <title>Fallback Resource</title>
595
596 <dl>
597 <dt>Description:</dt>
598 <dd>You want a single resource (say, a certain file, like index.php) to
599 handle all requests that come to a particular directory, except those
600 that should go to an existing resource such as an image, or a css file.</dd>
601
602 <dt>Solution:</dt>
603 <dd>
604 <p>As of version 2.2.16, you should use the <directive
605 module="mod_dir">FallbackResource</directive> directive for this:</p>
606
607 <example>
608 &lt;Directory /var/www/my_blog&gt;<br />
609 <indent>
610   FallbackResource index.php<br />
611 </indent>
612 &lt;/Directory&gt;
613 </example>
614
615 <p>However, in earlier versions of Apache, or if your needs are more
616 complicated than this, you can use a variation of the following rewrite
617 set to accomplish the same thing:</p>
618
619 <example>
620 &lt;Directory /var/www/my_blog&gt;<br />
621 <indent>
622   RewriteBase /my_blog<br />
623 <br />
624   RewriteCond /var/www/my_blog/%{REQUEST_FILENAME} !-f<br />
625   RewriteCond /var/www/my_blog/%{REQUEST_FILENAME} !-d<br />
626   RewriteRule ^ index.php [PT]<br />
627 </indent>
628 &lt;/Directory&gt;
629 </example>
630
631 <p>If, on the other hand, you wish to pass the requested URI as a query
632 string argument to index.php, you can replace that RewriteRule with:</p>
633
634 <example>
635   RewriteRule (.*) index.php?$1 [PT,QSA]
636 </example>
637
638 <p>Note that these rulesets can be used in a <code>.htaccess</code>
639 file, as well as in a &lt;Directory&gt; block.</p>
640
641 </dd>
642
643 </dl>
644
645 </section>
646
647 </manualpage>