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