]> granicus.if.org Git - apache/blob - docs/manual/rewrite/advanced.html.en
update transformation
[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.3</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.3</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 and tricks 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="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"><pre>
68 user1  physical_host_of_user1
69 user2  physical_host_of_user2
70 :      :
71 </pre></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"><pre>
77 /u/user1/anypath
78 </pre></div>
79
80   <p>to</p>
81
82 <div class="example"><pre>
83 http://physical_host_of_user1/u/user/anypath
84 </pre></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"><pre>
92 RewriteEngine on
93
94 RewriteMap      users-to-hosts   txt:/path/to/map.users-to-hosts
95
96 RewriteRule   ^/u/<strong>([^/]+)</strong>/?(.*)   http://<strong>${users-to-hosts:$1|server0}</strong>/u/$1/$2
97 </pre></div>
98     </dd>
99   </dl>
100
101 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
102 <div class="section">
103 <h2><a name="on-the-fly-content" id="on-the-fly-content">On-the-fly Content-Regeneration</a></h2>
104
105   
106
107   <dl>
108     <dt>Description:</dt>
109
110     <dd>
111       <p>We wish to dynamically generate content, but store it
112       statically once it is generated. This rule will check for the
113       existence of the static file, and if it's not there, generate
114       it. The static files can be removed periodically, if desired (say,
115       via cron) and will be regenerated on demand.</p>
116     </dd>
117
118     <dt>Solution:</dt>
119
120     <dd>
121       This is done via the following ruleset:
122
123 <div class="example"><pre>
124 # This example is valid in per-directory context only
125 RewriteCond %{REQUEST_FILENAME}   <strong>!-s</strong>
126 RewriteRule ^page\.<strong>html</strong>$          page.<strong>cgi</strong>   [T=application/x-httpd-cgi,L]
127 </pre></div>
128
129       <p>Here a request for <code>page.html</code> leads to an
130       internal run of a corresponding <code>page.cgi</code> if
131       <code>page.html</code> is missing or has filesize
132       null. The trick here is that <code>page.cgi</code> is a
133       CGI script which (additionally to its <code>STDOUT</code>)
134       writes its output to the file <code>page.html</code>.
135       Once it has completed, the server sends out
136       <code>page.html</code>. When the webmaster wants to force
137       a refresh of the contents, he just removes
138       <code>page.html</code> (typically from <code>cron</code>).</p>
139     </dd>
140   </dl>
141
142 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
143 <div class="section">
144 <h2><a name="load-balancing" id="load-balancing">Load Balancing</a></h2>
145
146   
147
148   <dl>
149     <dt>Description:</dt>
150
151     <dd>
152       <p>We wish to randomly distribute load across several servers
153       using mod_rewrite.</p>
154     </dd>
155
156     <dt>Solution:</dt>
157
158     <dd>
159       <p>We'll use <code class="directive"><a href="../mod/mod_rewrite.html#rewritemap">RewriteMap</a></code> and a list of servers
160       to accomplish this.</p>
161
162 <div class="example"><pre>
163 RewriteEngine on
164 RewriteMap lb rnd:/path/to/serverlist.txt
165
166 RewriteRule ^/(.*) http://${lb:servers}/$1 [P,L]
167 </pre></div>
168
169 <p><code>serverlist.txt</code> will contain a list of the servers:</p>
170
171 <div class="example"><pre>
172 ## serverlist.txt
173
174 servers one.example.com|two.example.com|three.example.com
175 </pre></div>
176
177 <p>If you want one particular server to get more of the load than the
178 others, add it more times to the list.</p>
179
180    </dd>
181
182    <dt>Discussion</dt>
183    <dd>
184 <p>Apache comes with a load-balancing module -
185 <code class="module"><a href="../mod/mod_proxy_balancer.html">mod_proxy_balancer</a></code> - which is far more flexible and
186 featureful than anything you can cobble together using mod_rewrite.</p>
187    </dd>
188   </dl>
189
190 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
191 <div class="section">
192 <h2><a name="autorefresh" id="autorefresh">Document With Autorefresh</a></h2>
193
194   
195
196   <dl>
197     <dt>Description:</dt>
198
199     <dd>
200       <p>Wouldn't it be nice, while creating a complex web page, if
201       the web browser would automatically refresh the page every
202       time we save a new version from within our editor?
203       Impossible?</p>
204     </dd>
205
206     <dt>Solution:</dt>
207
208     <dd>
209       <p>No! We just combine the MIME multipart feature, the
210       web server NPH feature, and the URL manipulation power of
211       <code class="module"><a href="../mod/mod_rewrite.html">mod_rewrite</a></code>. First, we establish a new
212       URL feature: Adding just <code>:refresh</code> to any
213       URL causes the 'page' to be refreshed every time it is
214       updated on the filesystem.</p>
215
216 <div class="example"><pre>
217 RewriteRule   ^(/[uge]/[^/]+/?.*):refresh  /internal/cgi/apache/nph-refresh?f=$1
218 </pre></div>
219
220       <p>Now when we reference the URL</p>
221
222 <div class="example"><pre>
223 /u/foo/bar/page.html:refresh
224 </pre></div>
225
226       <p>this leads to the internal invocation of the URL</p>
227
228 <div class="example"><pre>
229 /internal/cgi/apache/nph-refresh?f=/u/foo/bar/page.html
230 </pre></div>
231
232       <p>The only missing part is the NPH-CGI script. Although
233       one would usually say "left as an exercise to the reader"
234       ;-) I will provide this, too.</p>
235
236 <div class="example"><pre>
237 #!/sw/bin/perl
238 ##
239 ##  nph-refresh -- NPH/CGI script for auto refreshing pages
240 ##  Copyright (c) 1997 Ralf S. Engelschall, All Rights Reserved.
241 ##
242 $| = 1;
243
244 #   split the QUERY_STRING variable
245 @pairs = split(/&amp;/, $ENV{'QUERY_STRING'});
246 foreach $pair (@pairs) {
247 ($name, $value) = split(/=/, $pair);
248 $name =~ tr/A-Z/a-z/;
249 $name = 'QS_' . $name;
250 $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
251 eval "\$$name = \"$value\"";
252 }
253 $QS_s = 1 if ($QS_s eq '');
254 $QS_n = 3600 if ($QS_n eq '');
255 if ($QS_f eq '') {
256 print "HTTP/1.0 200 OK\n";
257 print "Content-type: text/html\n\n";
258 print "&amp;lt;b&amp;gt;ERROR&amp;lt;/b&amp;gt;: No file given\n";
259 exit(0);
260 }
261 if (! -f $QS_f) {
262 print "HTTP/1.0 200 OK\n";
263 print "Content-type: text/html\n\n";
264 print "&amp;lt;b&amp;gt;ERROR&amp;lt;/b&amp;gt;: File $QS_f not found\n";
265 exit(0);
266 }
267
268 sub print_http_headers_multipart_begin {
269 print "HTTP/1.0 200 OK\n";
270 $bound = "ThisRandomString12345";
271 print "Content-type: multipart/x-mixed-replace;boundary=$bound\n";
272 &amp;print_http_headers_multipart_next;
273 }
274
275 sub print_http_headers_multipart_next {
276 print "\n--$bound\n";
277 }
278
279 sub print_http_headers_multipart_end {
280 print "\n--$bound--\n";
281 }
282
283 sub displayhtml {
284 local($buffer) = @_;
285 $len = length($buffer);
286 print "Content-type: text/html\n";
287 print "Content-length: $len\n\n";
288 print $buffer;
289 }
290
291 sub readfile {
292 local($file) = @_;
293 local(*FP, $size, $buffer, $bytes);
294 ($x, $x, $x, $x, $x, $x, $x, $size) = stat($file);
295 $size = sprintf("%d", $size);
296 open(FP, "&amp;lt;$file");
297 $bytes = sysread(FP, $buffer, $size);
298 close(FP);
299 return $buffer;
300 }
301
302 $buffer = &amp;readfile($QS_f);
303 &amp;print_http_headers_multipart_begin;
304 &amp;displayhtml($buffer);
305
306 sub mystat {
307 local($file) = $_[0];
308 local($time);
309
310 ($x, $x, $x, $x, $x, $x, $x, $x, $x, $mtime) = stat($file);
311 return $mtime;
312 }
313
314 $mtimeL = &amp;mystat($QS_f);
315 $mtime = $mtime;
316 for ($n = 0; $n &amp;lt; $QS_n; $n++) {
317 while (1) {
318     $mtime = &amp;mystat($QS_f);
319     if ($mtime ne $mtimeL) {
320         $mtimeL = $mtime;
321         sleep(2);
322         $buffer = &amp;readfile($QS_f);
323         &amp;print_http_headers_multipart_next;
324         &amp;displayhtml($buffer);
325         sleep(5);
326         $mtimeL = &amp;mystat($QS_f);
327         last;
328     }
329     sleep($QS_s);
330 }
331 }
332
333 &amp;print_http_headers_multipart_end;
334
335 exit(0);
336
337 ##EOF##
338 </pre></div>
339     </dd>
340   </dl>
341
342 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
343 <div class="section">
344 <h2><a name="structuredhomedirs" id="structuredhomedirs">Structured Userdirs</a></h2>
345
346   
347
348   <dl>
349     <dt>Description:</dt>
350
351     <dd>
352       <p>Some sites with thousands of users use a
353       structured homedir layout, <em>i.e.</em> each homedir is in a
354       subdirectory which begins (for instance) with the first
355       character of the username. So, <code>/~larry/anypath</code>
356       is <code>/home/<strong>l</strong>/larry/public_html/anypath</code>
357       while <code>/~waldo/anypath</code> is
358       <code>/home/<strong>w</strong>/waldo/public_html/anypath</code>.</p>
359     </dd>
360
361     <dt>Solution:</dt>
362
363     <dd>
364       <p>We use the following ruleset to expand the tilde URLs
365       into the above layout.</p>
366
367 <div class="example"><pre>
368 RewriteEngine on
369 RewriteRule   ^/~(<strong>([a-z])</strong>[a-z0-9]+)(.*)  /home/<strong>$2</strong>/$1/public_html$3
370 </pre></div>
371     </dd>
372   </dl>
373
374 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
375 <div class="section">
376 <h2><a name="redirectanchors" id="redirectanchors">Redirecting Anchors</a></h2>
377
378   
379
380   <dl>
381     <dt>Description:</dt>
382
383     <dd>
384     <p>By default, redirecting to an HTML anchor doesn't work,
385     because mod_rewrite escapes the <code>#</code> character,
386     turning it into <code>%23</code>. This, in turn, breaks the
387     redirection.</p>
388     </dd>
389
390     <dt>Solution:</dt>
391
392     <dd>
393       <p>Use the <code>[NE]</code> flag on the
394       <code>RewriteRule</code>. NE stands for No Escape.
395       </p>
396     </dd>
397
398     <dt>Discussion:</dt>
399     <dd>This technique will of course also work with other 
400     special characters that mod_rewrite, by default, URL-encodes.</dd>
401   </dl>
402
403 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
404 <div class="section">
405 <h2><a name="time-dependent" id="time-dependent">Time-Dependent Rewriting</a></h2>
406
407   
408
409   <dl>
410     <dt>Description:</dt>
411
412     <dd>
413       <p>We wish to use mod_rewrite to serve different content based on
414       the time of day.</p>
415     </dd>
416
417     <dt>Solution:</dt>
418
419     <dd>
420       <p>There are a lot of variables named <code>TIME_xxx</code>
421       for rewrite conditions. In conjunction with the special
422       lexicographic comparison patterns <code>&lt;STRING</code>,
423       <code>&gt;STRING</code> and <code>=STRING</code> we can
424       do time-dependent redirects:</p>
425
426 <div class="example"><pre>
427 RewriteEngine on
428 RewriteCond   %{TIME_HOUR}%{TIME_MIN} &gt;0700
429 RewriteCond   %{TIME_HOUR}%{TIME_MIN} &lt;1900
430 RewriteRule   ^foo\.html$             foo.day.html [L]
431 RewriteRule   ^foo\.html$             foo.night.html
432 </pre></div>
433
434       <p>This provides the content of <code>foo.day.html</code>
435       under the URL <code>foo.html</code> from
436       <code>07:01-18:59</code> and at the remaining time the
437       contents of <code>foo.night.html</code>.</p>
438
439       <div class="warning"><code class="module"><a href="../mod/mod_cache.html">mod_cache</a></code>, intermediate proxies
440       and browsers may each cache responses and cause the either page to be
441       shown outside of the time-window configured.
442       <code class="module"><a href="../mod/mod_expires.html">mod_expires</a></code> may be used to control this
443       effect. You are, of course, much better off simply serving the
444       content dynamically, and customizing it based on the time of day.</div>
445
446     </dd>
447   </dl>
448
449 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
450 <div class="section">
451 <h2><a name="setenvvars" id="setenvvars">Set Environment Variables Based On URL Parts</a></h2>
452
453   
454
455   <dl>
456     <dt>Description:</dt>
457
458     <dd>
459       <p>At time, we want to maintain some kind of status when we
460       perform a rewrite. For example, you want to make a note that
461       you've done that rewrite, so that you can check later to see if a
462       request can via that rewrite. One way to do this is by setting an
463       environment variable.</p>
464     </dd>
465
466     <dt>Solution:</dt>
467
468     <dd>
469       <p>Use the [E] flag to set an environment variable.</p>
470
471 <div class="example"><pre>
472 RewriteEngine on
473 RewriteRule   ^/horse/(.*)   /pony/$1 [E=<strong>rewritten:1</strong>]
474 </pre></div>
475
476     <p>Later in your ruleset you might check for this environment
477     variable using a RewriteCond:</p>
478
479 <div class="example"><pre>
480 RewriteCond %{ENV:rewritten} =1
481 </pre></div>
482
483     </dd>
484   </dl>
485
486 </div></div>
487 <div class="bottomlang">
488 <p><span>Available Languages: </span><a href="../en/rewrite/avoid.html" title="English">&nbsp;en&nbsp;</a></p>
489 </div><div id="footer">
490 <p class="apache">Copyright 2009 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>
491 <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>
492 </body></html>