]> granicus.if.org Git - apache/blob - docs/manual/rewrite/rewritemap.xml
Actually show the example of how to do this.
[apache] / docs / manual / rewrite / rewritemap.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  Licensed to the Apache Software Foundation (ASF) under one or more
7  contributor license agreements.  See the NOTICE file distributed with
8  this work for additional information regarding copyright ownership.
9  The ASF licenses this file to You under the Apache License, Version 2.0
10  (the "License"); you may not use this file except in compliance with
11  the License.  You may obtain a copy of the License at
12
13      http://www.apache.org/licenses/LICENSE-2.0
14
15  Unless required by applicable law or agreed to in writing, software
16  distributed under the License is distributed on an "AS IS" BASIS,
17  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  See the License for the specific language governing permissions and
19  limitations under the License.
20 -->
21 <manualpage metafile="rewritemap.xml.meta">
22   <parentdocument href="./">Rewrite</parentdocument>
23   <title>Using RewriteMap</title>
24   <summary>
25
26     <p>This document supplements the <module>mod_rewrite</module>
27 <a href="../mod/mod_rewrite.html">reference documentation</a>. It describes
28 the use of the <directive module="mod_rewrite">RewriteMap</directive> directive,
29 and provides examples of each of the various <directive module="mod_rewrite"
30 >RewriteMap</directive> types.</p>
31
32     <note type="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.</note>
36
37   </summary>
38   <seealso><a href="../mod/mod_rewrite.html">Module documentation</a></seealso>
39   <seealso><a href="intro.html">mod_rewrite introduction</a></seealso>
40   <seealso><a href="remapping.html">Redirection and remapping</a></seealso>
41   <seealso><a href="access.html">Controlling access</a></seealso>
42   <seealso><a href="vhosts.html">Virtual hosts</a></seealso>
43   <seealso><a href="proxy.html">Proxying</a></seealso>
44   <seealso><a href="advanced.html">Advanced techniques</a></seealso>
45   <seealso><a href="avoid.html">When not to use mod_rewrite</a></seealso>
46
47   <section id="introduction">
48     <title>Introduction</title>
49
50    <p>
51    The <directive module="mod_rewrite">RewriteMap</directive> directive
52    defines an external function which can be called in the context of
53    <directive module="mod_rewrite">RewriteRule</directive> or
54    <directive module="mod_rewrite">RewriteCond</directive> directives to
55    perform rewriting that is too complicated, or too specialized to be
56    performed just by regular expressions. The source of this lookup can
57    be any of the types listed in the sections below, and enumerated in
58    the <directive module="mod_rewrite">RewriteMap</directive> reference
59    documentation.</p>
60
61    <p>The syntax of the <directive module="mod_rewrite">RewriteMap</directive>
62    directive is as follows:</p>
63
64 <highlight language="config">
65 RewriteMap <em>MapName</em> <em>MapType</em>:<em>MapSource</em>
66 </highlight>
67
68     <p>The <a id="mapfunc" name="mapfunc"><em>MapName</em></a> is an
69     arbitray name that you assign to the map, and which you will use in
70     directives later on. Arguments are passed to the map via the
71     following syntax:</p>
72
73     <p class="indent">
74       <strong>
75         <code>${</code> <em>MapName</em> <code>:</code> <em>LookupKey</em>
76         <code>}</code> <br/> <code>${</code> <em>MapName</em> <code>:</code>
77         <em>LookupKey</em> <code>|</code> <em>DefaultValue</em> <code>}</code>
78       </strong>
79     </p>
80
81     <p>When such a construct occurs, the map <em>MapName</em> is
82       consulted and the key <em>LookupKey</em> is looked-up. If the
83       key is found, the map-function construct is substituted by
84       <em>SubstValue</em>. If the key is not found then it is
85       substituted by <em>DefaultValue</em> or by the empty string
86       if no <em>DefaultValue</em> was specified.</p>
87
88     <p>For example, you can define a
89       <directive module="mod_rewrite">RewriteMap</directive> as:</p>
90     <highlight language="config">
91 RewriteMap examplemap "txt:/path/to/file/map.txt"
92     </highlight>
93     <p>You would then be able to use this map in a
94       <directive module="mod_rewrite">RewriteRule</directive> as follows:</p>
95       <highlight language="config">
96 RewriteRule "^/ex/(.*)" "${examplemap:$1}"
97       </highlight>
98
99 <p>A default value can be specified in the event that nothing is found
100 in the map:</p>
101
102 <highlight language="config">
103 RewriteRule "^/ex/(.*)" "${examplemap:$1|/not_found.html}"
104 </highlight>
105
106 <note><title>Per-directory and .htaccess context</title>
107 <p>
108 The <directive module="mod_rewrite">RewriteMap</directive> directive may not be
109 used in <directive module="core" type="section">Directory</directive> sections or
110 <code>.htaccess</code> files. You must
111 declare the map in server or virtualhost context. You may use the map,
112 once created, in your <directive module="mod_rewrite">RewriteRule</directive> and
113 <directive module="mod_rewrite">RewriteCond</directive> directives in those
114 scopes. You just can't <strong>declare</strong> it in those scopes.</p>
115 </note>
116
117 <p>The sections that follow describe the various <em>MapType</em>s that
118 may be used, and give examples of each.</p>
119   </section>
120
121   <section id="int">
122     <title>int: Internal Function</title>
123
124     <p>When a MapType of <code>int</code> is used, the MapSource is one
125     of the available internal <directive module="mod_rewrite">RewriteMap</directive>
126     functions.  Module authors can provide
127     additional internal functions by registering them with the
128     <code>ap_register_rewrite_mapfunc</code> API.
129     The functions that are provided by default are:
130     </p>
131
132     <ul>
133       <li><strong>toupper</strong>:<br/>
134              Converts the key to all upper case.</li>
135       <li><strong>tolower</strong>:<br/>
136              Converts the key to all lower case.</li>
137       <li><strong>escape</strong>:<br/>
138              Translates special characters in the key to
139             hex-encodings.</li>
140       <li><strong>unescape</strong>:<br/>
141              Translates hex-encodings in the key back to
142             special characters.</li>
143     </ul>
144
145     <p>
146     To use one of these functions, create a <directive module="mod_rewrite"
147     >RewriteMap</directive> referencing
148     the int function, and then use that in your <directive module="mod_rewrite"
149     >RewriteRule</directive>:
150     </p>
151
152    <p> <strong>Redirect a URI to an all-lowercase version of itself</strong></p>
153     <highlight language="config">
154 RewriteMap lc int:tolower
155 RewriteRule "(.*)" "${lc:$1}" [R]
156     </highlight>
157
158     <note>
159     <p>Please note that the example offered here is for
160     illustration purposes only, and is not a recommendation. If you want
161     to make URLs case-insensitive, consider using
162     <module>mod_speling</module> instead.
163     </p>
164     </note>
165
166   </section>
167
168   <section id="txt">
169     <title>txt: Plain text maps</title>
170
171     <p>When a MapType of <code>txt</code> is used, the MapSource is a filesystem path to a
172     plain-text mapping file, containing one space-separated key/value pair
173     per line. Optionally, a line may contain a comment, starting with
174     a '#' character.</p>
175
176     <p>A valid text rewrite map file will have the following syntax:</p>
177
178     <example>
179       # Comment line<br />
180       <strong><em>MatchingKey</em> <em>SubstValue</em></strong><br />
181       <strong><em>MatchingKey</em> <em>SubstValue</em></strong> # comment<br />
182     </example>
183
184     <p>When the <directive module="mod_rewrite">RewriteMap</directive> is invoked
185     the argument is looked for in the
186     first argument of a line, and, if found, the substitution value is
187     returned.</p>
188
189     <p>For example, we can use a mapfile to translate product names to
190     product IDs for easier-to-remember URLs, using the following
191     recipe:</p>
192 <p><strong>Product to ID configuration</strong></p>
193     <highlight language="config">
194 RewriteMap product2id "txt:/etc/apache2/productmap.txt"
195 RewriteRule "^/product/(.*)" "/prods.php?id=${product2id:$1|NOTFOUND}" [PT]
196     </highlight>
197
198     <p>We assume here that the <code>prods.php</code> script knows what
199     to do when it received an argument of <code>id=NOTFOUND</code> when
200     a product is not found in the lookup map.</p>
201
202     <p>The file <code>/etc/apache2/productmap.txt</code> then contains
203     the following:</p>
204
205     <example><title>Product to ID map</title>
206 ##<br />
207 ##  productmap.txt - Product to ID map file<br />
208 ##<br />
209 <br />
210 television 993<br />
211 stereo     198<br />
212 fishingrod 043<br />
213 basketball 418<br />
214 telephone  328
215     </example>
216
217     <p>Thus, when <code>http://example.com/product/television</code> is
218     requested, the <directive module="mod_rewrite">RewriteRule</directive> is
219     applied, and the request
220     is internally mapped to <code>/prods.php?id=993</code>.</p>
221
222     <note><title>Note: .htaccess files</title>
223     The example given is crafted to be used in server or virtualhost
224     scope. If you're planning to use this in a <code>.htaccess</code>
225     file, you'll need to remove the leading slash from the rewrite
226     pattern in order for it to match anything:
227     <highlight language="config">
228 RewriteRule "^product/(.*)" "/prods.php?id=${product2id:$1|NOTFOUND}" [PT]
229     </highlight>
230     </note>
231
232     <note><title>Cached lookups</title>
233     <p>
234     The looked-up keys are cached by httpd until the <code>mtime</code>
235     (modified time) of the mapfile changes, or the httpd server is
236     restarted. This ensures better performance on maps that are called
237     by many requests.
238     </p>
239     </note>
240
241   </section>
242   <section id="rnd">
243     <title>rnd: Randomized Plain Text</title>
244
245     <p>When a MapType of <code>rnd</code> is used, the MapSource is a
246     filesystem path to a plain-text mapping file, each line of which
247     contains a key, and one or more values separated by <code>|</code>.
248     One of these values will be chosen at random if the key is
249     matched.</p>
250
251     <p>For example, you can use the following map
252     file and directives to provide a random load balancing between
253     several back-end servers, via a reverse-proxy. Images are sent
254     to one of the servers in the 'static' pool, while everything
255     else is sent to one of the 'dynamic' pool.</p>
256
257     <example><title>Rewrite map file</title>
258 ##<br />
259 ##  map.txt -- rewriting map<br />
260 ##<br />
261 <br />
262 static   www1|www2|www3|www4<br />
263 dynamic  www5|www6
264     </example>
265 <p><strong>Configuration directives</strong></p>
266     <highlight language="config">
267 RewriteMap servers "rnd:/path/to/file/map.txt"
268
269 RewriteRule "^/(.*\.(png|gif|jpg))" "http://${servers:static}/$1"  [NC,P,L]
270 RewriteRule "^/(.*)"                "http://${servers:dynamic}/$1" [P,L]
271     </highlight>
272
273     <p>So, when an image is requested and the first of these rules is
274     matched, <directive module="mod_rewrite">RewriteMap</directive> looks up the string
275     <code>static</code> in the map file, which returns one of the
276     specified hostnames at random, which is then used in the
277     <directive module="mod_rewrite">RewriteRule</directive> target.</p>
278
279     <p>If you wanted to have one of the servers more likely to be chosen
280     (for example, if one of the server has more memory than the others,
281     and so can handle more requests) simply list it more times in the
282     map file.</p>
283
284     <example>
285 static   www1|www1|www2|www3|www4
286     </example>
287
288   </section>
289
290   <section id="dbm">
291     <title>dbm: DBM Hash File</title>
292
293     <p>When a MapType of <code>dbm</code> is used, the MapSource is a
294     filesystem path to a DBM database file containing key/value pairs to
295     be used in the mapping. This works exactly the same way as the
296     <code>txt</code> map, but is much faster, because a DBM is indexed,
297     whereas a text file is not. This allows more rapid access to the
298     desired key.</p>
299
300     <p>You may optionally specify a particular dbm type:</p>
301
302  <highlight language="config">
303 RewriteMap examplemap "dbm=sdbm:/etc/apache/mapfile.dbm"
304  </highlight>
305
306     <p>The type can be <code>sdbm</code>, <code>gdbm</code>, <code>ndbm</code> 
307     or <code>db</code>.
308     However, it is recommended that you just use the <a
309     href="../programs/httxt2dbm.html">httxt2dbm</a> utility that is
310     provided with Apache HTTP Server, as it will use the correct DBM library,
311     matching the one that was used when httpd itself was built.</p>
312
313     <p>To create a dbm file, first create a text map file as described
314     in the <a href="#txt">txt</a> section. Then run
315     <code>httxt2dbm</code>:</p>
316
317 <example>
318 $ httxt2dbm -i mapfile.txt -o mapfile.map
319 </example>
320
321 <p>You can then reference the resulting file in your
322 <directive module="mod_rewrite">RewriteMap</directive> directive:</p>
323
324 <highlight language="config">
325 RewriteMap mapname "dbm:/etc/apache/mapfile.map"
326 </highlight>
327
328 <note>
329 <p>Note that with some dbm types, more than one file is generated, with
330 a common base name. For example, you may have two files named
331 <code>mapfile.map.dir</code> and <code>mapfiile.map.pag</code>. This is
332 normal, and you need only use the base name <code>mapfile.map</code> in
333 your <directive module="mod_rewrite">RewriteMap</directive> directive.</p>
334 </note>
335
336 <note><title>Cached lookups</title>
337 <p>
338 The looked-up keys are cached by httpd until the <code>mtime</code>
339 (modified time) of the mapfile changes, or the httpd server is
340 restarted. This ensures better performance on maps that are called
341 by many requests.
342 </p>
343 </note>
344
345   </section>
346
347   <section id="prg"><title>prg: External Rewriting Program</title>
348
349     <p>When a MapType of <code>prg</code> is used, the MapSource is a
350     filesystem path to an executable program which will providing the
351     mapping behavior. This can be a compiled binary file, or a program
352     in an interpreted language such as Perl or Python.</p>
353
354     <p>This program is started once, when the Apache HTTP Server is
355     started, and then communicates with the rewriting engine via
356     <code>STDIN</code> and <code>STDOUT</code>. That is, for each map
357     function lookup, it expects one argument via <code>STDIN</code>, and
358     should return one new-line terminated response string on
359     <code>STDOUT</code>. If there is no corresponding lookup value, the
360     map program should return the four-character string
361     "<code>NULL</code>" to indicate this.</p>
362
363     <p>External rewriting programs are not started if they're defined in
364     a context that does not have <directive
365     module="mod_rewrite">RewriteEngine</directive> set to
366     <code>on</code>.</p>
367
368     <p>By default, external rewriting programs are run as the
369     user:group who started httpd. This can be changed on UNIX systems
370     by passing user name and group name as third argument to
371     <directive module="mod_rewrite">RewriteMap</directive> in the
372     <code>username:groupname</code> format.</p>
373
374     <p>This feature utilizes the <code>rewrite-map</code> mutex,
375     which is required for reliable communication with the program.
376     The mutex mechanism and lock file can be configured with the
377     <directive module="core">Mutex</directive> directive.</p>
378
379     <p>A simple example is shown here which will replace all dashes with
380     underscores in a request URI.</p>
381
382     <p><strong>Rewrite configuration</strong></p>
383     <highlight language="config">
384 RewriteMap d2u "prg:/www/bin/dash2under.programlisting" apache:apache
385 RewriteRule "-" "${d2u:%{REQUEST_URI}}"
386     </highlight>
387
388     <p><strong>dash2under.pl</strong></p>
389     <highlight language="perl">
390 #!/usr/bin/perl
391 $| = 1; # Turn off I/O buffering
392 while (&lt;STDIN&gt;) {
393     s/-/_/g; # Replace dashes with underscores
394     print $_;
395 }
396     </highlight>
397
398 <note><title>Caution!</title>
399 <ul>
400 <li>Keep your rewrite map program as simple as possible. If the program
401 hangs, it will cause httpd to wait indefinitely for a response from the
402 map, which will, in turn, cause httpd to stop responding to
403 requests.</li>
404 <li>Be sure to turn off buffering in your program. In Perl this is done
405 by the second line in the example script: <code>$| = 1;</code> This will
406 of course vary in other languages. Buffered I/O will cause httpd to wait
407 for the output, and so it will hang.</li>
408 <li>Remember that there is only one copy of the program, started at
409 server startup. All requests will need to go through this one bottleneck.
410 This can cause significant slowdowns if many requests must go through
411 this process, or if the script itself is very slow.</li>
412 </ul>
413 </note>
414
415 </section>
416
417
418   <section id="dbd">
419     <title>dbd or fastdbd: SQL Query</title>
420
421     <p>When a MapType of <code>dbd</code> or <code>fastdbd</code> is
422     used, the MapSource is a SQL SELECT statement that takes a single
423     argument and returns a single value.</p>
424
425     <p><module>mod_dbd</module> will need to be configured to point at
426     the right database for this statement to be executed.</p>
427
428     <p>There are two forms of this MapType.
429     Using a MapType of <code>dbd</code> causes the query to be
430     executed with each map request, while using <code>fastdbd</code>
431     caches the database lookups internally. So, while
432     <code>fastdbd</code> is more efficient, and therefore faster, it
433     won't pick up on changes to the database until the server is
434     restarted.</p>
435
436     <p>If a query returns more than one row, a random row from
437     the result set is used.</p>
438
439     <example><title>Example</title>
440     <highlight language="config">
441 RewriteMap myquery "fastdbd:SELECT destination FROM rewrite WHERE source = %s"
442     </highlight>
443     </example>
444
445   </section>
446   <section id="summary">
447     <title>Summary</title>
448
449     <p>The <directive module="mod_rewrite">RewriteMap</directive> directive can
450     occur more than once. For each mapping-function use one
451     <directive module="mod_rewrite">RewriteMap</directive> directive to declare
452     its rewriting mapfile.</p>
453
454     <p>While you cannot <strong>declare</strong> a map in
455     per-directory context (<code>.htaccess</code> files or
456     <directive module="core" type="section">Directory</directive> blocks) it is
457     possible to <strong>use</strong> this map in per-directory context.</p>
458
459   </section>
460 </manualpage>