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