]> granicus.if.org Git - apache/blob - docs/manual/rewrite/advanced.html.en
s/2011/2012/g
[apache] / docs / manual / rewrite / advanced.html.en
1 <?xml version="1.0" encoding="ISO-8859-1"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head><!--
4         XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5               This file is generated from xml source: DO NOT EDIT
6         XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7       -->
8 <title>Advanced Techniques with mod_rewrite - Apache HTTP Server</title>
9 <link href="../style/css/manual.css" rel="stylesheet" media="all" type="text/css" title="Main stylesheet" />
10 <link href="../style/css/manual-loose-100pc.css" rel="alternate stylesheet" media="all" type="text/css" title="No Sidebar - Default font size" />
11 <link href="../style/css/manual-print.css" rel="stylesheet" media="print" type="text/css" />
12 <link href="../images/favicon.ico" rel="shortcut icon" /></head>
13 <body id="manual-page"><div id="page-header">
14 <p class="menu"><a href="../mod/">Modules</a> | <a href="../mod/directives.html">Directives</a> | <a href="../faq/">FAQ</a> | <a href="../glossary.html">Glossary</a> | <a href="../sitemap.html">Sitemap</a></p>
15 <p class="apache">Apache HTTP Server Version 2.5</p>
16 <img alt="" src="../images/feather.gif" /></div>
17 <div class="up"><a href="./"><img title="&lt;-" alt="&lt;-" src="../images/left.gif" /></a></div>
18 <div id="path">
19 <a href="http://www.apache.org/">Apache</a> &gt; <a href="http://httpd.apache.org/">HTTP Server</a> &gt; <a href="http://httpd.apache.org/docs/">Documentation</a> &gt; <a href="../">Version 2.5</a> &gt; <a href="./">Rewrite</a></div><div id="page-content"><div id="preamble"><h1>Advanced Techniques with mod_rewrite</h1>
20 <div class="toplang">
21 <p><span>Available Languages: </span><a href="../en/rewrite/avoid.html" title="English">&nbsp;en&nbsp;</a></p>
22 </div>
23
24
25 <p>This document supplements the <code class="module"><a href="../mod/mod_rewrite.html">mod_rewrite</a></code>
26 <a href="../mod/mod_rewrite.html">reference documentation</a>. It provides
27 a few advanced techniques using mod_rewrite.</p>
28
29 <div class="warning">Note that many of these examples won't work unchanged in your
30 particular server configuration, so it's important that you understand
31 them, rather than merely cutting and pasting the examples into your
32 configuration.</div>
33
34 </div>
35 <div id="quickview"><ul id="toc"><li><img alt="" src="../images/down.gif" /> <a href="#sharding">URL-based sharding accross multiple backends</a></li>
36 <li><img alt="" src="../images/down.gif" /> <a href="#on-the-fly-content">On-the-fly Content-Regeneration</a></li>
37 <li><img alt="" src="../images/down.gif" /> <a href="#load-balancing">Load Balancing</a></li>
38 <li><img alt="" src="../images/down.gif" /> <a href="#autorefresh">Document With Autorefresh</a></li>
39 <li><img alt="" src="../images/down.gif" /> <a href="#structuredhomedirs">Structured Userdirs</a></li>
40 <li><img alt="" src="../images/down.gif" /> <a href="#redirectanchors">Redirecting Anchors</a></li>
41 <li><img alt="" src="../images/down.gif" /> <a href="#time-dependent">Time-Dependent Rewriting</a></li>
42 <li><img alt="" src="../images/down.gif" /> <a href="#setenvvars">Set Environment Variables Based On URL Parts</a></li>
43 </ul><h3>See also</h3><ul class="seealso"><li><a href="../mod/mod_rewrite.html">Module documentation</a></li><li><a href="intro.html">mod_rewrite introduction</a></li><li><a href="remapping.html">Redirection and remapping</a></li><li><a href="access.html">Controlling access</a></li><li><a href="vhosts.html">Virtual hosts</a></li><li><a href="proxy.html">Proxying</a></li><li><a href="rewritemap.html">Using RewriteMap</a></li><li><a href="avoid.html">When not to use mod_rewrite</a></li></ul></div>
44 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
45 <div class="section">
46 <h2><a name="sharding" id="sharding">URL-based sharding accross multiple backends</a></h2>
47
48   
49
50   <dl>
51     <dt>Description:</dt>
52
53     <dd>
54       <p>A common technique for distributing the burden of
55       server load or storage space is called "sharding".
56       When using this method, a front-end server will use the
57       url to consistently "shard" users or objects to separate
58       backend servers.</p>
59     </dd>
60
61     <dt>Solution:</dt>
62
63     <dd>
64       <p>A mapping is maintained, from users to target servers, in
65       external map files. They look like:</p>
66
67 <div class="example"><p><code>
68 user1  physical_host_of_user1<br />
69 user2  physical_host_of_user2<br />
70 :      :
71 </code></p></div>
72
73   <p>We put this into a <code>map.users-to-hosts</code> file. The
74     aim is to map;</p>
75
76 <div class="example"><p><code>
77 /u/user1/anypath
78 </code></p></div>
79
80   <p>to</p>
81
82 <div class="example"><p><code>
83 http://physical_host_of_user1/u/user/anypath
84 </code></p></div>
85
86       <p>thus every URL path need not be valid on every backend physical
87       host. The following ruleset does this for us with the help of the map
88       files assuming that server0 is a default server which will be used if
89       a user has no entry in the map:</p>
90
91 <div class="example"><p><code>
92 RewriteEngine on<br />
93 <br />
94 RewriteMap      users-to-hosts   txt:/path/to/map.users-to-hosts<br />
95 <br />
96 RewriteRule   ^/u/<strong>([^/]+)</strong>/?(.*)   http://<strong>${users-to-hosts:$1|server0}</strong>/u/$1/$2
97 </code></p></div>
98     </dd>
99   </dl>
100
101   <p>See the <code class="directive"><a href="../mod/mod_rewrite.html#rewritemap">RewriteMap</a></code>
102   documentation for more discussion of the syntax of this directive.</p>
103
104 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
105 <div class="section">
106 <h2><a name="on-the-fly-content" id="on-the-fly-content">On-the-fly Content-Regeneration</a></h2>
107
108   
109
110   <dl>
111     <dt>Description:</dt>
112
113     <dd>
114       <p>We wish to dynamically generate content, but store it
115       statically once it is generated. This rule will check for the
116       existence of the static file, and if it's not there, generate
117       it. The static files can be removed periodically, if desired (say,
118       via cron) and will be regenerated on demand.</p>
119     </dd>
120
121     <dt>Solution:</dt>
122
123     <dd>
124       This is done via the following ruleset:
125
126 <div class="example"><p><code>
127 # This example is valid in per-directory context only<br />
128 RewriteCond %{REQUEST_URI}   <strong>!-U</strong><br />
129 RewriteRule ^(.+)\.html$          /regenerate_page.cgi   [PT,L]
130 </code></p></div>
131
132     <p>The <code>-U</code> operator determines whether the test string
133     (in this case, <code>REQUEST_URI</code>) is a valid URL. It does
134     this via a subrequest. In the event that this subrequest fails -
135     that is, the requested resource doesn't exist - this rule invokes
136     the CGI program <code>/regenerate_page.cgi</code>, which generates
137     the requested resource and saves it into the document directory, so
138     that the next time it is requested, a static copy can be served.</p>
139
140     <p>In this way, documents that are infrequently updated can be served in
141     static form. if documents need to be refreshed, they can be deleted
142     from the document directory, and they will then be regenerated the
143     next time they are requested.</p>
144     </dd>
145   </dl>
146
147 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
148 <div class="section">
149 <h2><a name="load-balancing" id="load-balancing">Load Balancing</a></h2>
150
151   
152
153   <dl>
154     <dt>Description:</dt>
155
156     <dd>
157       <p>We wish to randomly distribute load across several servers
158       using mod_rewrite.</p>
159     </dd>
160
161     <dt>Solution:</dt>
162
163     <dd>
164       <p>We'll use <code class="directive"><a href="../mod/mod_rewrite.html#rewritemap">RewriteMap</a></code> and a list of servers
165       to accomplish this.</p>
166
167 <div class="example"><p><code>
168 RewriteEngine on<br />
169 RewriteMap lb rnd:/path/to/serverlist.txt<br />
170 <br />
171 RewriteRule ^/(.*) http://${lb:servers}/$1 [P,L]
172 </code></p></div>
173
174 <p><code>serverlist.txt</code> will contain a list of the servers:</p>
175
176 <div class="example"><p><code>
177 ## serverlist.txt<br />
178 <br />
179 servers one.example.com|two.example.com|three.example.com<br />
180 </code></p></div>
181
182 <p>If you want one particular server to get more of the load than the
183 others, add it more times to the list.</p>
184
185    </dd>
186
187    <dt>Discussion</dt>
188    <dd>
189 <p>Apache comes with a load-balancing module -
190 <code class="module"><a href="../mod/mod_proxy_balancer.html">mod_proxy_balancer</a></code> - which is far more flexible and
191 featureful than anything you can cobble together using mod_rewrite.</p>
192    </dd>
193   </dl>
194
195 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
196 <div class="section">
197 <h2><a name="autorefresh" id="autorefresh">Document With Autorefresh</a></h2>
198
199   
200
201
202
203   <dl>
204     <dt>Description:</dt>
205
206     <dd>
207       <p>Wouldn't it be nice, while creating a complex web page, if
208       the web browser would automatically refresh the page every
209       time we save a new version from within our editor?
210       Impossible?</p>
211     </dd>
212
213     <dt>Solution:</dt>
214
215     <dd>
216       <p>No! We just combine the MIME multipart feature, the
217       web server NPH feature, and the URL manipulation power of
218       <code class="module"><a href="../mod/mod_rewrite.html">mod_rewrite</a></code>. First, we establish a new
219       URL feature: Adding just <code>:refresh</code> to any
220       URL causes the 'page' to be refreshed every time it is
221       updated on the filesystem.</p>
222
223 <div class="example"><p><code>
224 RewriteRule   ^(/[uge]/[^/]+/?.*):refresh  /internal/cgi/apache/nph-refresh?f=$1
225 </code></p></div>
226
227       <p>Now when we reference the URL</p>
228
229 <div class="example"><p><code>
230 /u/foo/bar/page.html:refresh
231 </code></p></div>
232
233       <p>this leads to the internal invocation of the URL</p>
234
235 <div class="example"><p><code>
236 /internal/cgi/apache/nph-refresh?f=/u/foo/bar/page.html
237 </code></p></div>
238
239       <p>The only missing part is the NPH-CGI script. Although
240       one would usually say "left as an exercise to the reader"
241       ;-) I will provide this, too.</p>
242
243 <div class="example"><pre>
244 #!/sw/bin/perl
245 ##
246 ##  nph-refresh -- NPH/CGI script for auto refreshing pages
247 ##  Copyright (c) 1997 Ralf S. Engelschall, All Rights Reserved.
248 ##
249 $| = 1;
250
251 #   split the QUERY_STRING variable
252 @pairs = split(/&amp;/, $ENV{'QUERY_STRING'});
253 foreach $pair (@pairs) {
254 ($name, $value) = split(/=/, $pair);
255 $name =~ tr/A-Z/a-z/;
256 $name = 'QS_' . $name;
257 $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
258 eval "\$$name = \"$value\"";
259 }
260 $QS_s = 1 if ($QS_s eq '');
261 $QS_n = 3600 if ($QS_n eq '');
262 if ($QS_f eq '') {
263 print "HTTP/1.0 200 OK\n";
264 print "Content-type: text/html\n\n";
265 print "&amp;lt;b&amp;gt;ERROR&amp;lt;/b&amp;gt;: No file given\n";
266 exit(0);
267 }
268 if (! -f $QS_f) {
269 print "HTTP/1.0 200 OK\n";
270 print "Content-type: text/html\n\n";
271 print "&amp;lt;b&amp;gt;ERROR&amp;lt;/b&amp;gt;: File $QS_f not found\n";
272 exit(0);
273 }
274
275 sub print_http_headers_multipart_begin {
276 print "HTTP/1.0 200 OK\n";
277 $bound = "ThisRandomString12345";
278 print "Content-type: multipart/x-mixed-replace;boundary=$bound\n";
279 &amp;print_http_headers_multipart_next;
280 }
281
282 sub print_http_headers_multipart_next {
283 print "\n--$bound\n";
284 }
285
286 sub print_http_headers_multipart_end {
287 print "\n--$bound--\n";
288 }
289
290 sub displayhtml {
291 local($buffer) = @_;
292 $len = length($buffer);
293 print "Content-type: text/html\n";
294 print "Content-length: $len\n\n";
295 print $buffer;
296 }
297
298 sub readfile {
299 local($file) = @_;
300 local(*FP, $size, $buffer, $bytes);
301 ($x, $x, $x, $x, $x, $x, $x, $size) = stat($file);
302 $size = sprintf("%d", $size);
303 open(FP, "&amp;lt;$file");
304 $bytes = sysread(FP, $buffer, $size);
305 close(FP);
306 return $buffer;
307 }
308
309 $buffer = &amp;readfile($QS_f);
310 &amp;print_http_headers_multipart_begin;
311 &amp;displayhtml($buffer);
312
313 sub mystat {
314 local($file) = $_[0];
315 local($time);
316
317 ($x, $x, $x, $x, $x, $x, $x, $x, $x, $mtime) = stat($file);
318 return $mtime;
319 }
320
321 $mtimeL = &amp;mystat($QS_f);
322 $mtime = $mtime;
323 for ($n = 0; $n &amp;lt; $QS_n; $n++) {
324 while (1) {
325     $mtime = &amp;mystat($QS_f);
326     if ($mtime ne $mtimeL) {
327         $mtimeL = $mtime;
328         sleep(2);
329         $buffer = &amp;readfile($QS_f);
330         &amp;print_http_headers_multipart_next;
331         &amp;displayhtml($buffer);
332         sleep(5);
333         $mtimeL = &amp;mystat($QS_f);
334         last;
335     }
336     sleep($QS_s);
337 }
338 }
339
340 &amp;print_http_headers_multipart_end;
341
342 exit(0);
343
344 ##EOF##
345 </pre></div>
346     </dd>
347   </dl>
348
349 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
350 <div class="section">
351 <h2><a name="structuredhomedirs" id="structuredhomedirs">Structured Userdirs</a></h2>
352
353   
354
355   <dl>
356     <dt>Description:</dt>
357
358     <dd>
359       <p>Some sites with thousands of users use a
360       structured homedir layout, <em>i.e.</em> each homedir is in a
361       subdirectory which begins (for instance) with the first
362       character of the username. So, <code>/~larry/anypath</code>
363       is <code>/home/<strong>l</strong>/larry/public_html/anypath</code>
364       while <code>/~waldo/anypath</code> is
365       <code>/home/<strong>w</strong>/waldo/public_html/anypath</code>.</p>
366     </dd>
367
368     <dt>Solution:</dt>
369
370     <dd>
371       <p>We use the following ruleset to expand the tilde URLs
372       into the above layout.</p>
373
374 <div class="example"><p><code>
375 RewriteEngine on<br />
376 RewriteRule   ^/~(<strong>([a-z])</strong>[a-z0-9]+)(.*)  /home/<strong>$2</strong>/$1/public_html$3
377 </code></p></div>
378     </dd>
379   </dl>
380
381 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
382 <div class="section">
383 <h2><a name="redirectanchors" id="redirectanchors">Redirecting Anchors</a></h2>
384
385   
386
387   <dl>
388     <dt>Description:</dt>
389
390     <dd>
391     <p>By default, redirecting to an HTML anchor doesn't work,
392     because mod_rewrite escapes the <code>#</code> character,
393     turning it into <code>%23</code>. This, in turn, breaks the
394     redirection.</p>
395     </dd>
396
397     <dt>Solution:</dt>
398
399     <dd>
400       <p>Use the <code>[NE]</code> flag on the
401       <code>RewriteRule</code>. NE stands for No Escape.
402       </p>
403     </dd>
404
405     <dt>Discussion:</dt>
406     <dd>This technique will of course also work with other
407     special characters that mod_rewrite, by default, URL-encodes.</dd>
408   </dl>
409
410 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
411 <div class="section">
412 <h2><a name="time-dependent" id="time-dependent">Time-Dependent Rewriting</a></h2>
413
414   
415
416   <dl>
417     <dt>Description:</dt>
418
419     <dd>
420       <p>We wish to use mod_rewrite to serve different content based on
421       the time of day.</p>
422     </dd>
423
424     <dt>Solution:</dt>
425
426     <dd>
427       <p>There are a lot of variables named <code>TIME_xxx</code>
428       for rewrite conditions. In conjunction with the special
429       lexicographic comparison patterns <code>&lt;STRING</code>,
430       <code>&gt;STRING</code> and <code>=STRING</code> we can
431       do time-dependent redirects:</p>
432
433 <div class="example"><p><code>
434 RewriteEngine on<br />
435 RewriteCond   %{TIME_HOUR}%{TIME_MIN} &gt;0700<br />
436 RewriteCond   %{TIME_HOUR}%{TIME_MIN} &lt;1900<br />
437 RewriteRule   ^foo\.html$             foo.day.html [L]<br />
438 RewriteRule   ^foo\.html$             foo.night.html
439 </code></p></div>
440
441       <p>This provides the content of <code>foo.day.html</code>
442       under the URL <code>foo.html</code> from
443       <code>07:01-18:59</code> and at the remaining time the
444       contents of <code>foo.night.html</code>.</p>
445
446       <div class="warning"><code class="module"><a href="../mod/mod_cache.html">mod_cache</a></code>, intermediate proxies
447       and browsers may each cache responses and cause the either page to be
448       shown outside of the time-window configured.
449       <code class="module"><a href="../mod/mod_expires.html">mod_expires</a></code> may be used to control this
450       effect. You are, of course, much better off simply serving the
451       content dynamically, and customizing it based on the time of day.</div>
452
453     </dd>
454   </dl>
455
456 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
457 <div class="section">
458 <h2><a name="setenvvars" id="setenvvars">Set Environment Variables Based On URL Parts</a></h2>
459
460   
461
462   <dl>
463     <dt>Description:</dt>
464
465     <dd>
466       <p>At time, we want to maintain some kind of status when we
467       perform a rewrite. For example, you want to make a note that
468       you've done that rewrite, so that you can check later to see if a
469       request can via that rewrite. One way to do this is by setting an
470       environment variable.</p>
471     </dd>
472
473     <dt>Solution:</dt>
474
475     <dd>
476       <p>Use the [E] flag to set an environment variable.</p>
477
478 <div class="example"><p><code>
479 RewriteEngine on<br />
480 RewriteRule   ^/horse/(.*)   /pony/$1 [E=<strong>rewritten:1</strong>]
481 </code></p></div>
482
483     <p>Later in your ruleset you might check for this environment
484     variable using a RewriteCond:</p>
485
486 <div class="example"><p><code>
487 RewriteCond %{ENV:rewritten} =1
488 </code></p></div>
489
490     <p>Note that environment variables do not survive an external
491     redirect. You might consider using the [CO] flag to set a
492     cookie.</p>
493
494     </dd>
495   </dl>
496
497 </div></div>
498 <div class="bottomlang">
499 <p><span>Available Languages: </span><a href="../en/rewrite/avoid.html" title="English">&nbsp;en&nbsp;</a></p>
500 </div><div id="footer">
501 <p class="apache">Copyright 2012 The Apache Software Foundation.<br />Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a>.</p>
502 <p class="menu"><a href="../mod/">Modules</a> | <a href="../mod/directives.html">Directives</a> | <a href="../faq/">FAQ</a> | <a href="../glossary.html">Glossary</a> | <a href="../sitemap.html">Sitemap</a></p></div>
503 </body></html>