]> granicus.if.org Git - apache/blob - docs/manual/rewrite/remapping.xml
Quote {Alias,Redirect,ScriptAlias}{,Match} arguments.
[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 <highlight language="config">
75 RewriteEngine  on
76 RewriteRule    ^<strong>/foo</strong>\.html$  <strong>/bar</strong>.html [PT]
77 </highlight>
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 <highlight language="config">
106 RewriteEngine  on
107 RewriteRule    ^<strong>/foo</strong>\.html$  <strong>bar</strong>.html  [<strong>R</strong>]
108 </highlight>
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     <highlight language="config">
120 Redirect "/foo.html" "/bar.html"
121     </highlight>
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 <highlight language="config">
149 #With mod_rewrite
150 RewriteEngine on
151 RewriteRule   ^/docs/(.+)  http://new.example.com/docs/$1  [R,L]
152 </highlight>
153
154 <highlight language="config">
155 #With RedirectMatch
156 RedirectMatch "^/docs/(.*)" "http://new.example.com/docs/$1"
157 </highlight>
158
159 <highlight language="config">
160 #With Redirect
161 Redirect "/docs/" "http://new.example.com/docs/"
162 </highlight>
163     </dd>
164   </dl>
165
166 </section>
167
168 <section id="static-to-dynamic">
169
170   <title>From Static to Dynamic</title>
171
172   <dl>
173     <dt>Description:</dt>
174
175     <dd>
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>
180     </dd>
181
182     <dt>Solution:</dt>
183
184     <dd>
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>
191
192 <highlight language="config">
193 RewriteEngine  on
194 RewriteBase    /~quux/
195 RewriteRule    ^foo\.html$  foo.cgi &nbsp; [H=<strong>cgi-script</strong>]
196 </highlight>
197     </dd>
198   </dl>
199
200 </section>
201
202 <section id="backward-compatibility">
203
204   <title>Backward Compatibility for file extension change</title>
205
206   <dl>
207     <dt>Description:</dt>
208
209     <dd>
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>
214     </dd>
215
216     <dt>Solution:</dt>
217
218     <dd>
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>
222
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 &lt;Directory "/var/www/htdocs"&gt;
228     RewriteEngine on
229     RewriteBase /var/www/htdocs
230
231     RewriteCond $1.php -f
232     RewriteCond $1.html !-f
233     RewriteRule ^(.*).html$ $1.php
234 &lt;/Directory&gt;
235 </highlight>
236     </dd>
237
238     <dt>Discussion</dt>
239     <dd>
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>
248
249     <p>This ruleset is designed to use in a per-directory context (In a
250     &lt;Directory&gt; 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>
255     </dd>
256   </dl>
257
258 </section>
259
260 <section id="canonicalhost">
261
262 <title>Canonical Hostnames</title>
263
264       <dl>
265         <dt>Description:</dt>
266
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>
273
274         <dt>Solution:</dt>
275
276         <dd>
277
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
281 hostname(s).</p>
282
283 <highlight language="config">
284 &lt;VirtualHost *:80&gt;
285   ServerName undesired.example.com
286   ServerAlias example.com notthis.example.com
287
288   Redirect "/" "http://www.example.com/"
289 &lt;/VirtualHost&gt;
290
291 &lt;VirtualHost *:80&gt;
292   ServerName www.example.com
293 &lt;/VirtualHost&gt;
294 </highlight>
295
296 <p>You can alternatively accomplish this using the
297 <directive module="core" type="section">If</directive>
298 directive:</p>
299
300 <highlight language="config">
301 &lt;If "%{HTTP_HOST} != 'www.example.com'"&gt;
302     Redirect "/" "http://www.example.com/"
303 &lt;/If&gt;
304 </highlight>
305
306 <p>Or, for example, to redirect a portion of your site to HTTPS, you
307 might do the following:</p>
308
309 <highlight language="config">
310 &lt;If "%{SERVER_PROTOCOL} != 'HTTPS'"&gt;
311     Redirect "/admin/" "https://www.example.com/admin/"
312 &lt;/If&gt;
313 </highlight>
314
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>
318
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]
325 </highlight>
326
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]
332 </highlight>
333
334         <p>
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
339         recipe:</p>
340
341 <highlight language="config">
342 RewriteCond %{HTTP_HOST} !^www\. [NC]
343 RewriteCond %{HTTP_HOST} !^$
344 RewriteRule ^/?(.*) http://www.%{HTTP_HOST}/$1 [L,R,NE]
345 </highlight>
346
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>
350         </dd>
351       </dl>
352
353 </section>
354
355 <section id="multipledirs">
356
357   <title>Search for pages in more than one directory</title>
358
359   <dl>
360     <dt>Description:</dt>
361
362     <dd>
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>
367     </dd>
368
369     <dt>Solution:</dt>
370
371     <dd>
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>
375
376 <highlight language="config">
377 RewriteEngine on
378
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]
383
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]
388
389 #   else go on for other Alias or ScriptAlias directives,
390 #   etc.
391 RewriteRule   ^  -  [PT]
392 </highlight>
393     </dd>
394   </dl>
395
396 </section>
397
398 <section id="archive-access-multiplexer">
399
400   <title>Redirecting to Geographically Distributed Servers</title>
401
402   <dl>
403     <dt>Description:</dt>
404
405     <dd>
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
408     located.</p>
409     </dd>
410
411     <dt>Solution:</dt>
412
413     <dd>
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>
419
420 <highlight language="config">
421 HostnameLookups on
422 RewriteEngine on
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]
426 </highlight>
427
428 <example>
429 ##  map.mirrors -- Multiplexing Map<br />
430 <br />
431 de        http://www.example.de/<br />
432 uk        http://www.example.uk/<br />
433 com       http://www.example.com/<br />
434 ##EOF##
435 </example>
436     </dd>
437
438     <dt>Discussion</dt>
439     <dd>
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>
444
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
449     file.</p>
450     </dd>
451   </dl>
452
453 </section>
454
455 <section id="canonicalurl">
456
457 <title>Canonical URLs</title>
458
459 <dl>
460  <dt>Description:</dt>
461
462    <dd>
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>
469    </dd>
470
471    <dt>Solution:</dt>
472
473      <dd>
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>
479
480 <highlight language="config">RewriteRule   ^/(puppies|canines)/(.*)    /dogs/$2  [R]</highlight>
481         </dd>
482
483      <dt>Discussion:</dt>
484      <dd>
485      This should really be accomplished with Redirect or RedirectMatch
486      directives:
487
488      <highlight language="config">
489 RedirectMatch "^/(puppies|canines)/(.*)" "/dogs/$2"
490      </highlight>
491      </dd>
492       </dl>
493
494 </section>
495
496 <section id="moveddocroot">
497
498   <title>Moved <code>DocumentRoot</code></title>
499
500   <dl>
501     <dt>Description:</dt>
502
503     <dd>
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>
510 </dd>
511
512     <dt>Solution:</dt>
513
514     <dd>
515       <p>We redirect the URL <code>/</code> to
516       <code>/about/</code>:
517       </p>
518
519 <highlight language="config">
520 RewriteEngine on
521 RewriteRule   ^/$  /about/  [<strong>R</strong>]
522 </highlight>
523
524 <p>Note that this can also be handled using the <directive
525 module="mod_alias">RedirectMatch</directive> directive:</p>
526
527 <highlight language="config">
528 RedirectMatch "^/$" "http://example.com/about/"
529 </highlight>
530
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>
539 </dd>
540 </dl>
541
542 </section>
543
544 <section id="fallback-resource">
545 <title>Fallback Resource</title>
546
547 <dl>
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>
552
553 <dt>Solution:</dt>
554 <dd>
555 <p>As of version 2.2.16, you should use the <directive
556 module="mod_dir">FallbackResource</directive> directive for this:</p>
557
558 <highlight language="config">
559 &lt;Directory "/var/www/my_blog"&gt;
560   FallbackResource index.php
561 &lt;/Directory&gt;
562 </highlight>
563
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>
567
568 <highlight language="config">
569 &lt;Directory "/var/www/my_blog"&gt;
570   RewriteBase /my_blog
571
572   RewriteCond /var/www/my_blog/%{REQUEST_FILENAME} !-f
573   RewriteCond /var/www/my_blog/%{REQUEST_FILENAME} !-d
574   RewriteRule ^ index.php [PT]
575 &lt;/Directory&gt;
576 </highlight>
577
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>
580
581 <highlight language="config">
582 RewriteRule (.*) index.php?$1 [PT,QSA]
583 </highlight>
584
585 <p>Note that these rulesets can be used in a <code>.htaccess</code>
586 file, as well as in a &lt;Directory&gt; block.</p>
587
588 </dd>
589
590 </dl>
591
592 </section>
593
594 <section id="rewrite-query">
595 <title>Rewrite query string</title>
596
597 <dl>
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
601 of the URL.</dd>
602
603 <dt>Solutions:</dt>
604 <dd>
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 '&amp;&amp;' in the 
609 substitutions.</p>
610 <ul>
611   <li>This solution removes the matching key and value:
612
613 <highlight language="config">
614 # Remove mykey=???
615 RewriteCond %{QUERY_STRING} (.*(?:^|&amp;))mykey=([^&amp;]*)&amp;?(.*)&amp;?$
616 RewriteRule (.*) $1?%1%3
617 </highlight>
618   </li>
619
620   <li>This solution uses the captured value in the URL subsitution,
621   discarding the rest of the original query by appending a '?':
622
623 <highlight language="config">
624 # Copy from query string to PATH_INFO
625 RewriteCond %{QUERY_STRING} (.*(?:^|&amp;))mykey=([^&amp;]*)&amp;?(.*)&amp;?$
626 RewriteRule (.*) $1/products/%2/? [PT]
627 </highlight>
628   </li>
629
630   <li>This solution checks the captured value in a subsequent condition:
631
632 <highlight language="config">
633 # Capture the value of mykey in the query string
634 RewriteCond %{QUERY_STRING} (.*(?:^|&amp;))mykey=([^&amp;]*)&amp;?(.*)&amp;?$
635 RewriteCond %2 !=not-so-secret-value 
636 RewriteRule (.*) - [F]
637 </highlight>
638   </li>
639
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]
646 </highlight>
647   </li>
648 </ul>
649
650 </dd>
651
652 </dl>
653 </section>
654
655
656 </manualpage>