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