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 --><title>mod_rewrite - Apache HTTP Server</title><link href="../style/css/manual.css" rel="stylesheet" media="all" type="text/css" title="Main stylesheet" /><link href="../style/css/manual-loose-100pc.css" rel="alternate stylesheet" media="all" type="text/css" title="No Sidebar - Default font size" /><link href="../images/favicon.ico" rel="shortcut icon" /></head><body><div id="page-header"><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><p class="apache">Apache HTTP Server Version 2.0</p><img alt="" src="../images/feather.gif" /></div><div class="up"><a href="./"><img title="<-" alt="<-" src="../images/left.gif" /></a></div><div id="path"><a href="http://www.apache.org/">Apache</a> > <a href="http://httpd.apache.org/">HTTP Server</a> > <a href="http://httpd.apache.org/docs-project/">Documentation</a> > <a href="../">Version 2.0</a> > <a href="./">Modules</a></div><div id="page-content"><div id="preamble"><h1>Apache Module mod_rewrite</h1><table class="module"><tr><th><a href="module-dict.html#Description">Description:
8 </a></th><td>Provides a rule-based rewriting engine to rewrite requested
9 URLs on the fly</td></tr><tr><th><a href="module-dict.html#Status">Status:
10 </a></th><td>Extension</td></tr><tr><th><a href="module-dict.html#ModuleIdentifier">Module Identifier:
11 </a></th><td>rewrite_module</td></tr><tr><th><a href="module-dict.html#SourceFile">Source File:
12 </a></th><td>mod_rewrite.c</td></tr><tr><th><a href="module-dict.html#Compatibility">Compatibility:
13 </a></th><td>Available in Apache 1.3 and later</td></tr></table><h3>Summary</h3>
15 <p>``The great thing about mod_rewrite is it gives you
16 all the configurability and flexibility of Sendmail.
17 The downside to mod_rewrite is that it gives you all
18 the configurability and flexibility of Sendmail.''</p>
20 <p class="cite">-- <cite>Brian Behlendorf</cite><br />
26 <p>`` Despite the tons of examples and docs,
27 mod_rewrite is voodoo. Damned cool voodoo, but still
30 <p class="cite">-- <cite>Brian Moore</cite><br />
36 <p>Welcome to mod_rewrite, the Swiss Army Knife of URL
39 <p>This module uses a rule-based rewriting engine (based on a
40 regular-expression parser) to rewrite requested URLs on the
41 fly. It supports an unlimited number of rules and an
42 unlimited number of attached rule conditions for each rule to
43 provide a really flexible and powerful URL manipulation
44 mechanism. The URL manipulations can depend on various tests,
45 for instance server variables, environment variables, HTTP
46 headers, time stamps and even external database lookups in
47 various formats can be used to achieve a really granular URL
50 <p>This module operates on the full URLs (including the
51 path-info part) both in per-server context
52 (<code>httpd.conf</code>) and per-directory context
53 (<code>.htaccess</code>) and can even generate query-string
54 parts on result. The rewritten result can lead to internal
55 sub-processing, external request redirection or even to an
56 internal proxy throughput.</p>
58 <p>But all this functionality and flexibility has its
59 drawback: complexity. So don't expect to understand this
60 entire module in just one day.</p>
62 <p>This module was invented and originally written in April
63 1996 and gifted exclusively to the The Apache Group in July 1997
67 <a href="http://www.engelschall.com/"><code>Ralf S.
68 Engelschall</code></a><br />
69 <a href="mailto:rse@engelschall.com"><code>rse@engelschall.com</code></a><br />
70 <a href="http://www.engelschall.com/"><code>www.engelschall.com</code></a>
72 </div><div id="quickview"><h3 class="directives">Directives</h3><ul id="toc"><li><img alt="" src="../images/down.gif" /> <a href="#rewritebase">RewriteBase</a></li><li><img alt="" src="../images/down.gif" /> <a href="#rewritecond">RewriteCond</a></li><li><img alt="" src="../images/down.gif" /> <a href="#rewriteengine">RewriteEngine</a></li><li><img alt="" src="../images/down.gif" /> <a href="#rewritelock">RewriteLock</a></li><li><img alt="" src="../images/down.gif" /> <a href="#rewritelog">RewriteLog</a></li><li><img alt="" src="../images/down.gif" /> <a href="#rewriteloglevel">RewriteLogLevel</a></li><li><img alt="" src="../images/down.gif" /> <a href="#rewritemap">RewriteMap</a></li><li><img alt="" src="../images/down.gif" /> <a href="#rewriteoptions">RewriteOptions</a></li><li><img alt="" src="../images/down.gif" /> <a href="#rewriterule">RewriteRule</a></li></ul><h3>Topics</h3><ul id="topics"><li><img alt="" src="../images/down.gif" /> <a href="#Internal">Interal Processing</a></li><li><img alt="" src="../images/down.gif" /> <a href="#EnvVar">Environment Variables</a></li><li><img alt="" src="../images/down.gif" /> <a href="#Solutions">Practical Solutions</a></li></ul></div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div><div class="section"><h2><a name="Internal" id="Internal">Interal Processing</a></h2>
74 <p>The internal processing of this module is very complex but
75 needs to be explained once even to the average user to avoid
76 common mistakes and to let you exploit its full
79 <h3><a name="InternalAPI" id="InternalAPI">API Phases</a></h3>
81 <p>First you have to understand that when Apache processes a
82 HTTP request it does this in phases. A hook for each of these
83 phases is provided by the Apache API. Mod_rewrite uses two of
84 these hooks: the URL-to-filename translation hook which is
85 used after the HTTP request has been read but before any
86 authorization starts and the Fixup hook which is triggered
87 after the authorization phases and after the per-directory
88 config files (<code>.htaccess</code>) have been read, but
89 before the content handler is activated.</p>
91 <p>So, after a request comes in and Apache has determined the
92 corresponding server (or virtual server) the rewriting engine
93 starts processing of all mod_rewrite directives from the
94 per-server configuration in the URL-to-filename phase. A few
95 steps later when the final data directories are found, the
96 per-directory configuration directives of mod_rewrite are
97 triggered in the Fixup phase. In both situations mod_rewrite
98 rewrites URLs either to new URLs or to filenames, although
99 there is no obvious distinction between them. This is a usage
100 of the API which was not intended to be this way when the API
101 was designed, but as of Apache 1.x this is the only way
102 mod_rewrite can operate. To make this point more clear
103 remember the following two points:</p>
106 <li>Although mod_rewrite rewrites URLs to URLs, URLs to
107 filenames and even filenames to filenames, the API
108 currently provides only a URL-to-filename hook. In Apache
109 2.0 the two missing hooks will be added to make the
110 processing more clear. But this point has no drawbacks for
111 the user, it is just a fact which should be remembered:
112 Apache does more in the URL-to-filename hook than the API
116 Unbelievably mod_rewrite provides URL manipulations in
117 per-directory context, <em>i.e.</em>, within
118 <code>.htaccess</code> files, although these are reached
119 a very long time after the URLs have been translated to
120 filenames. It has to be this way because
121 <code>.htaccess</code> files live in the filesystem, so
122 processing has already reached this stage. In other
123 words: According to the API phases at this time it is too
124 late for any URL manipulations. To overcome this chicken
125 and egg problem mod_rewrite uses a trick: When you
126 manipulate a URL/filename in per-directory context
127 mod_rewrite first rewrites the filename back to its
128 corresponding URL (which is usually impossible, but see
129 the <code>RewriteBase</code> directive below for the
130 trick to achieve this) and then initiates a new internal
131 sub-request with the new URL. This restarts processing of
134 <p>Again mod_rewrite tries hard to make this complicated
135 step totally transparent to the user, but you should
136 remember here: While URL manipulations in per-server
137 context are really fast and efficient, per-directory
138 rewrites are slow and inefficient due to this chicken and
139 egg problem. But on the other hand this is the only way
140 mod_rewrite can provide (locally restricted) URL
141 manipulations to the average user.</p>
145 <p>Don't forget these two points!</p>
148 <h3><a name="InternalRuleset" id="InternalRuleset">Ruleset Processing</a></h3>
150 <p>Now when mod_rewrite is triggered in these two API phases, it
151 reads the configured rulesets from its configuration
152 structure (which itself was either created on startup for
153 per-server context or during the directory walk of the Apache
154 kernel for per-directory context). Then the URL rewriting
155 engine is started with the contained ruleset (one or more
156 rules together with their conditions). The operation of the
157 URL rewriting engine itself is exactly the same for both
158 configuration contexts. Only the final result processing is
161 <p>The order of rules in the ruleset is important because the
162 rewriting engine processes them in a special (and not very
163 obvious) order. The rule is this: The rewriting engine loops
164 through the ruleset rule by rule (<code class="directive"><a href="#rewriterule">RewriteRule</a></code> directives) and
165 when a particular rule matches it optionally loops through
166 existing corresponding conditions (<code>RewriteCond</code>
167 directives). For historical reasons the conditions are given
168 first, and so the control flow is a little bit long-winded. See
169 Figure 1 for more details.</p>
171 <img src="../images/mod_rewrite_fig1.gif" width="428" height="385" alt="[Needs graphics capability to display]" /><br />
172 <dfn>Figure 1:</dfn>The control flow through the rewriting ruleset
174 <p>As you can see, first the URL is matched against the
175 <em>Pattern</em> of each rule. When it fails mod_rewrite
176 immediately stops processing this rule and continues with the
177 next rule. If the <em>Pattern</em> matches, mod_rewrite looks
178 for corresponding rule conditions. If none are present, it
179 just substitutes the URL with a new value which is
180 constructed from the string <em>Substitution</em> and goes on
181 with its rule-looping. But if conditions exist, it starts an
182 inner loop for processing them in the order that they are
183 listed. For conditions the logic is different: we don't match
184 a pattern against the current URL. Instead we first create a
185 string <em>TestString</em> by expanding variables,
186 back-references, map lookups, <em>etc.</em> and then we try
187 to match <em>CondPattern</em> against it. If the pattern
188 doesn't match, the complete set of conditions and the
189 corresponding rule fails. If the pattern matches, then the
190 next condition is processed until no more conditions are
191 available. If all conditions match, processing is continued
192 with the substitution of the URL with
193 <em>Substitution</em>.</p>
197 <h3><a name="quoting" id="quoting">Quoting Special Characters</a></h3>
199 <p>As of Apache 1.3.20, special characters in
200 <em>TestString</em> and <em>Substitution</em> strings can be
201 escaped (that is, treated as normal characters without their
202 usual special meaning) by prefixing them with a slosh ('\')
203 character. In other words, you can include an actual
204 dollar-sign character in a <em>Substitution</em> string by
205 using '<code>\$</code>'; this keeps mod_rewrite from trying
206 to treat it as a backreference.</p>
209 <h3><a name="InternalBackRefs" id="InternalBackRefs">Regex Back-Reference Availability</a></h3>
211 <p>One important thing here has to be remembered: Whenever you
212 use parentheses in <em>Pattern</em> or in one of the
213 <em>CondPattern</em>, back-references are internally created
214 which can be used with the strings <code>$N</code> and
215 <code>%N</code> (see below). These are available for creating
216 the strings <em>Substitution</em> and <em>TestString</em>.
217 Figure 2 shows to which locations the back-references are
218 transfered for expansion.</p>
221 <img src="../images/mod_rewrite_fig2.gif" width="381" height="179" alt="[Needs graphics capability to display]" /><br />
222 <dfn>Figure 2:</dfn> The back-reference flow through a rule.
224 <p>We know this was a crash course on mod_rewrite's internal
225 processing. But you will benefit from this knowledge when
226 reading the following documentation of the available
230 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div><div class="section"><h2><a name="EnvVar" id="EnvVar">Environment Variables</a></h2>
232 <p>This module keeps track of two additional (non-standard)
233 CGI/SSI environment variables named <code>SCRIPT_URL</code>
234 and <code>SCRIPT_URI</code>. These contain the
235 <em>logical</em> Web-view to the current resource, while the
236 standard CGI/SSI variables <code>SCRIPT_NAME</code> and
237 <code>SCRIPT_FILENAME</code> contain the <em>physical</em>
240 <p>Notice: These variables hold the URI/URL <em>as they were
241 initially requested</em>, <em>i.e.</em>, <em>before</em> any
242 rewriting. This is important because the rewriting process is
243 primarily used to rewrite logical URLs to physical
246 <div class="example"><h3>Example</h3><pre>
247 SCRIPT_NAME=/sw/lib/w3s/tree/global/u/rse/.www/index.html
248 SCRIPT_FILENAME=/u/rse/.www/index.html
250 SCRIPT_URI=http://en1.engelschall.com/u/rse/
253 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div><div class="section"><h2><a name="Solutions" id="Solutions">Practical Solutions</a></h2>
255 <p>We also have an <a href="../misc/rewriteguide.html">URL
256 Rewriting Guide</a> available, which provides a collection of
257 practical solutions for URL-based problems. There you can
258 find real-life rulesets and additional information about
260 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div><div class="directive-section"><h2><a name="RewriteBase" id="RewriteBase">RewriteBase</a> <a name="rewritebase" id="rewritebase">Directive</a></h2><table class="directive"><tr><th><a href="directive-dict.html#Description">Description:
261 </a></th><td>Sets the base URL for per-directory rewrites</td></tr><tr><th><a href="directive-dict.html#Syntax">Syntax:
262 </a></th><td>RewriteBase <em>URL-path</em></td></tr><tr><th><a href="directive-dict.html#Default">Default:
263 </a></th><td><code>See usage for information.</code></td></tr><tr><th><a href="directive-dict.html#Context">Context:
264 </a></th><td>directory, .htaccess</td></tr><tr><th><a href="directive-dict.html#Override">Override:
265 </a></th><td>FileInfo</td></tr><tr><th><a href="directive-dict.html#Status">Status:
266 </a></th><td>Extension</td></tr><tr><th><a href="directive-dict.html#Module">Module:
267 </a></th><td>mod_rewrite</td></tr></table>
268 <p>The <code class="directive">RewriteBase</code> directive explicitly
269 sets the base URL for per-directory rewrites. As you will see
270 below, <code class="directive"><a href="#rewriterule">RewriteRule</a></code>
271 can be used in per-directory config files
272 (<code>.htaccess</code>). There it will act locally,
273 <em>i.e.</em>, the local directory prefix is stripped at this
274 stage of processing and your rewriting rules act only on the
275 remainder. At the end it is automatically added back to the
276 path. The default setting is; <code class="directive">RewriteBase</code> <em>physical-directory-path</em></p>
278 <p>When a substitution occurs for a new URL, this module has
279 to re-inject the URL into the server processing. To be able
280 to do this it needs to know what the corresponding URL-prefix
281 or URL-base is. By default this prefix is the corresponding
282 filepath itself. <strong>But at most websites URLs are NOT
283 directly related to physical filename paths, so this
284 assumption will usually be wrong!</strong> There you have to
285 use the <code>RewriteBase</code> directive to specify the
286 correct URL-prefix.</p>
288 <div class="note"> If your webserver's URLs are <strong>not</strong> directly
289 related to physical file paths, you have to use
290 <code class="directive">RewriteBase</code> in every <code>.htaccess</code>
291 files where you want to use <code class="directive"><a href="#rewriterule">RewriteRule</a></code> directives.
294 <p> For example, assume the following per-directory config file:</p>
296 <div class="example"><pre>
298 # /abc/def/.htaccess -- per-dir config file for directory /abc/def
299 # Remember: /abc/def is the physical path of /xyz, <em>i.e.</em>, the server
300 # has a 'Alias /xyz /abc/def' directive <em>e.g.</em>
305 # let the server know that we were reached via /xyz and not
306 # via the physical path prefix /abc/def
309 # now the rewriting rules
310 RewriteRule ^oldstuff\.html$ newstuff.html
313 <p>In the above example, a request to
314 <code>/xyz/oldstuff.html</code> gets correctly rewritten to
315 the physical file <code>/abc/def/newstuff.html</code>.</p>
317 <div class="note"><h3>For Apache Hackers</h3>
318 <p>The following list gives detailed information about
319 the internal processing steps:</p>
325 /xyz/oldstuff.html -> /abc/def/oldstuff.html (per-server Alias)
326 /abc/def/oldstuff.html -> /abc/def/newstuff.html (per-dir RewriteRule)
327 /abc/def/newstuff.html -> /xyz/newstuff.html (per-dir RewriteBase)
328 /xyz/newstuff.html -> /abc/def/newstuff.html (per-server Alias)
331 /abc/def/newstuff.html
333 <p>This seems very complicated but is
334 the correct Apache internal processing, because the
335 per-directory rewriting comes too late in the
336 process. So, when it occurs the (rewritten) request
337 has to be re-injected into the Apache kernel! BUT:
338 While this seems like a serious overhead, it really
339 isn't, because this re-injection happens fully
340 internally to the Apache server and the same
341 procedure is used by many other operations inside
342 Apache. So, you can be sure the design and
343 implementation is correct.</p>
346 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div><div class="directive-section"><h2><a name="RewriteCond" id="RewriteCond">RewriteCond</a> <a name="rewritecond" id="rewritecond">Directive</a></h2><table class="directive"><tr><th><a href="directive-dict.html#Description">Description:
347 </a></th><td>Defines a condition under which rewriting will take place
348 </td></tr><tr><th><a href="directive-dict.html#Syntax">Syntax:
349 </a></th><td> RewriteCond
350 <em>TestString</em> <em>CondPattern</em></td></tr><tr><th><a href="directive-dict.html#Default">Default:
351 </a></th><td><code>None</code></td></tr><tr><th><a href="directive-dict.html#Context">Context:
352 </a></th><td>server config, virtual host, directory, .htaccess</td></tr><tr><th><a href="directive-dict.html#Override">Override:
353 </a></th><td>FileInfo</td></tr><tr><th><a href="directive-dict.html#Status">Status:
354 </a></th><td>Extension</td></tr><tr><th><a href="directive-dict.html#Module">Module:
355 </a></th><td>mod_rewrite</td></tr></table>
356 <p>The <code class="directive">RewriteCond</code> directive defines a
357 rule condition. Precede a <code class="directive"><a href="#rewriterule">RewriteRule</a></code> directive with one
358 or more <code class="directive">RewriteCond</code> directives. The following
359 rewriting rule is only used if its pattern matches the current
360 state of the URI <strong>and</strong> if these additional
361 conditions apply too.</p>
363 <p><em>TestString</em> is a string which can contains the
364 following expanded constructs in addition to plain text:</p>
368 <strong>RewriteRule backreferences</strong>: These are
369 backreferences of the form
372 <strong><code>$N</code></strong>
374 (0 <= N <= 9) which provide access to the grouped
375 parts (parenthesis!) of the pattern from the
376 corresponding <code>RewriteRule</code> directive (the one
377 following the current bunch of <code>RewriteCond</code>
382 <strong>RewriteCond backreferences</strong>: These are
383 backreferences of the form
386 <strong><code>%N</code></strong>
388 (1 <= N <= 9) which provide access to the grouped
389 parts (parentheses!) of the pattern from the last matched
390 <code>RewriteCond</code> directive in the current bunch
395 <strong>RewriteMap expansions</strong>: These are
396 expansions of the form
399 <strong><code>${mapname:key|default}</code></strong>
401 See <a href="#mapfunc">the documentation for
402 RewriteMap</a> for more details.
406 <strong>Server-Variables</strong>: These are variables of
410 <strong><code>%{</code> <em>NAME_OF_VARIABLE</em>
411 <code>}</code></strong>
413 where <em>NAME_OF_VARIABLE</em> can be a string taken
414 from the following list:
418 <th>HTTP headers:</th> <th>connection & request:</th> <th />
423 HTTP_USER_AGENT<br />
428 HTTP_PROXY_CONNECTION<br />
438 SCRIPT_FILENAME<br />
448 <th>server internals:</th> <th>system stuff:</th> <th>specials:</th>
458 SERVER_PROTOCOL<br />
459 SERVER_SOFTWARE<br />
477 REQUEST_FILENAME<br />
484 <p>These variables all
485 correspond to the similarly named HTTP
486 MIME-headers, C variables of the Apache server or
487 <code>struct tm</code> fields of the Unix system.
488 Most are documented elsewhere in the Manual or in
489 the CGI specification. Those that are special to
490 mod_rewrite include:</p>
493 <dt><code>IS_SUBREQ</code></dt>
495 <dd>Will contain the text "true" if the request
496 currently being processed is a sub-request,
497 "false" otherwise. Sub-requests may be generated
498 by modules that need to resolve additional files
499 or URIs in order to complete their tasks.</dd>
501 <dt><code>API_VERSION</code></dt>
503 <dd>This is the version of the Apache module API
504 (the internal interface between server and
505 module) in the current httpd build, as defined in
506 include/ap_mmn.h. The module API version
507 corresponds to the version of Apache in use (in
508 the release version of Apache 1.3.14, for
509 instance, it is 19990320:10), but is mainly of
510 interest to module authors.</dd>
512 <dt><code>THE_REQUEST</code></dt>
514 <dd>The full HTTP request line sent by the
515 browser to the server (e.g., "<code>GET
516 /index.html HTTP/1.1</code>"). This does not
517 include any additional headers sent by the
520 <dt><code>REQUEST_URI</code></dt>
522 <dd>The resource requested in the HTTP request
523 line. (In the example above, this would be
526 <dt><code>REQUEST_FILENAME</code></dt>
528 <dd>The full local filesystem path to the file or
529 script matching the request.</dd>
535 <p>Special Notes:</p>
538 <li>The variables SCRIPT_FILENAME and REQUEST_FILENAME
539 contain the same value, <em>i.e.</em>, the value of the
540 <code>filename</code> field of the internal
541 <code>request_rec</code> structure of the Apache server.
542 The first name is just the commonly known CGI variable name
543 while the second is the consistent counterpart to
544 REQUEST_URI (which contains the value of the
545 <code>uri</code> field of <code>request_rec</code>).</li>
547 <li>There is the special format:
548 <code>%{ENV:variable}</code> where <em>variable</em> can be
549 any environment variable. This is looked-up via internal
550 Apache structures and (if not found there) via
551 <code>getenv()</code> from the Apache server process.</li>
553 <li>There is the special format:
554 <code>%{HTTP:header}</code> where <em>header</em> can be
555 any HTTP MIME-header name. This is looked-up from the HTTP
556 request. Example: <code>%{HTTP:Proxy-Connection}</code> is
557 the value of the HTTP header
558 ``<code>Proxy-Connection:</code>''.</li>
560 <li>There is the special format
561 <code>%{LA-U:variable}</code> for look-aheads which perform
562 an internal (URL-based) sub-request to determine the final
563 value of <em>variable</em>. Use this when you want to use a
564 variable for rewriting which is actually set later in an
565 API phase and thus is not available at the current stage.
566 For instance when you want to rewrite according to the
567 <code>REMOTE_USER</code> variable from within the
568 per-server context (<code>httpd.conf</code> file) you have
569 to use <code>%{LA-U:REMOTE_USER}</code> because this
570 variable is set by the authorization phases which come
571 <em>after</em> the URL translation phase where mod_rewrite
572 operates. On the other hand, because mod_rewrite implements
573 its per-directory context (<code>.htaccess</code> file) via
574 the Fixup phase of the API and because the authorization
575 phases come <em>before</em> this phase, you just can use
576 <code>%{REMOTE_USER}</code> there.</li>
578 <li>There is the special format:
579 <code>%{LA-F:variable}</code> which performs an internal
580 (filename-based) sub-request to determine the final value
581 of <em>variable</em>. Most of the time this is the same as
585 <p><em>CondPattern</em> is the condition pattern,
586 <em>i.e.</em>, a regular expression which is applied to the
587 current instance of the <em>TestString</em>, <em>i.e.</em>,
588 <em>TestString</em> is evaluated and then matched against
589 <em>CondPattern</em>.</p>
591 <p><strong>Remember:</strong> <em>CondPattern</em> is a
592 standard <em>Extended Regular Expression</em> with some
596 <li>You can prefix the pattern string with a
597 '<code>!</code>' character (exclamation mark) to specify a
598 <strong>non</strong>-matching pattern.</li>
601 There are some special variants of <em>CondPatterns</em>.
602 Instead of real regular expression strings you can also
603 use one of the following:
606 <li>'<strong><CondPattern</strong>' (is lexically
608 Treats the <em>CondPattern</em> as a plain string and
609 compares it lexically to <em>TestString</em>. True if
610 <em>TestString</em> is lexically lower than
611 <em>CondPattern</em>.</li>
613 <li>'<strong>>CondPattern</strong>' (is lexically
615 Treats the <em>CondPattern</em> as a plain string and
616 compares it lexically to <em>TestString</em>. True if
617 <em>TestString</em> is lexically greater than
618 <em>CondPattern</em>.</li>
620 <li>'<strong>=CondPattern</strong>' (is lexically
622 Treats the <em>CondPattern</em> as a plain string and
623 compares it lexically to <em>TestString</em>. True if
624 <em>TestString</em> is lexically equal to
625 <em>CondPattern</em>, i.e the two strings are exactly
626 equal (character by character). If <em>CondPattern</em>
627 is just <code>""</code> (two quotation marks) this
628 compares <em>TestString</em> to the empty string.</li>
630 <li>'<strong>-d</strong>' (is
631 <strong>d</strong>irectory)<br />
632 Treats the <em>TestString</em> as a pathname and tests
633 if it exists and is a directory.</li>
635 <li>'<strong>-f</strong>' (is regular
636 <strong>f</strong>ile)<br />
637 Treats the <em>TestString</em> as a pathname and tests
638 if it exists and is a regular file.</li>
640 <li>'<strong>-s</strong>' (is regular file with
641 <strong>s</strong>ize)<br />
642 Treats the <em>TestString</em> as a pathname and tests
643 if it exists and is a regular file with size greater
646 <li>'<strong>-l</strong>' (is symbolic
647 <strong>l</strong>ink)<br />
648 Treats the <em>TestString</em> as a pathname and tests
649 if it exists and is a symbolic link.</li>
651 <li>'<strong>-F</strong>' (is existing file via
653 Checks if <em>TestString</em> is a valid file and
654 accessible via all the server's currently-configured
655 access controls for that path. This uses an internal
656 subrequest to determine the check, so use it with care
657 because it decreases your servers performance!</li>
659 <li>'<strong>-U</strong>' (is existing URL via
661 Checks if <em>TestString</em> is a valid URL and
662 accessible via all the server's currently-configured
663 access controls for that path. This uses an internal
664 subrequest to determine the check, so use it with care
665 because it decreases your server's performance!</li>
668 <div class="note"><h3>Notice</h3>
669 All of these tests can
670 also be prefixed by an exclamation mark ('!') to
671 negate their meaning.
676 <p>Additionally you can set special flags for
677 <em>CondPattern</em> by appending</p>
680 <strong><code>[</code><em>flags</em><code>]</code></strong>
683 <p>as the third argument to the <code>RewriteCond</code>
684 directive. <em>Flags</em> is a comma-separated list of the
688 <li>'<strong><code>nocase|NC</code></strong>'
689 (<strong>n</strong>o <strong>c</strong>ase)<br />
690 This makes the test case-insensitive, <em>i.e.</em>, there
691 is no difference between 'A-Z' and 'a-z' both in the
692 expanded <em>TestString</em> and the <em>CondPattern</em>.
693 This flag is effective only for comparisons between
694 <em>TestString</em> and <em>CondPattern</em>. It has no
695 effect on filesystem and subrequest checks.</li>
698 '<strong><code>ornext|OR</code></strong>'
699 (<strong>or</strong> next condition)<br />
700 Use this to combine rule conditions with a local OR
701 instead of the implicit AND. Typical example:
703 <div class="example"><pre>
704 RewriteCond %{REMOTE_HOST} ^host1.* [OR]
705 RewriteCond %{REMOTE_HOST} ^host2.* [OR]
706 RewriteCond %{REMOTE_HOST} ^host3.*
707 RewriteRule ...some special stuff for any of these hosts...
710 Without this flag you would have to write the cond/rule
715 <p><strong>Example:</strong></p>
717 <p>To rewrite the Homepage of a site according to the
718 ``<code>User-Agent:</code>'' header of the request, you can
719 use the following: </p>
721 <div class="example"><pre>
722 RewriteCond %{HTTP_USER_AGENT} ^Mozilla.*
723 RewriteRule ^/$ /homepage.max.html [L]
725 RewriteCond %{HTTP_USER_AGENT} ^Lynx.*
726 RewriteRule ^/$ /homepage.min.html [L]
728 RewriteRule ^/$ /homepage.std.html [L]
731 <p>Interpretation: If you use Netscape Navigator as your
732 browser (which identifies itself as 'Mozilla'), then you
733 get the max homepage, which includes Frames, <em>etc.</em>
734 If you use the Lynx browser (which is Terminal-based), then
735 you get the min homepage, which contains no images, no
736 tables, <em>etc.</em> If you use any other browser you get
737 the standard homepage.</p>
739 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div><div class="directive-section"><h2><a name="RewriteEngine" id="RewriteEngine">RewriteEngine</a> <a name="rewriteengine" id="rewriteengine">Directive</a></h2><table class="directive"><tr><th><a href="directive-dict.html#Description">Description:
740 </a></th><td>Enables or disables runtime rewriting engine</td></tr><tr><th><a href="directive-dict.html#Syntax">Syntax:
741 </a></th><td>RewriteEngine on|off</td></tr><tr><th><a href="directive-dict.html#Default">Default:
742 </a></th><td><code>RewriteEngine off</code></td></tr><tr><th><a href="directive-dict.html#Context">Context:
743 </a></th><td>server config, virtual host, directory, .htaccess</td></tr><tr><th><a href="directive-dict.html#Override">Override:
744 </a></th><td>FileInfo</td></tr><tr><th><a href="directive-dict.html#Status">Status:
745 </a></th><td>Extension</td></tr><tr><th><a href="directive-dict.html#Module">Module:
746 </a></th><td>mod_rewrite</td></tr></table>
748 <p>The <code class="directive">RewriteEngine</code> directive enables or
749 disables the runtime rewriting engine. If it is set to
750 <code>off</code> this module does no runtime processing at
751 all. It does not even update the <code>SCRIPT_URx</code>
752 environment variables.</p>
754 <p>Use this directive to disable the module instead of
755 commenting out all the <code class="directive"><a href="#rewriterule">RewriteRule</a></code> directives!</p>
757 <p>Note that, by default, rewrite configurations are not
758 inherited. This means that you need to have a
759 <code>RewriteEngine on</code> directive for each virtual host
760 in which you wish to use it.</p>
761 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div><div class="directive-section"><h2><a name="RewriteLock" id="RewriteLock">RewriteLock</a> <a name="rewritelock" id="rewritelock">Directive</a></h2><table class="directive"><tr><th><a href="directive-dict.html#Description">Description:
762 </a></th><td>Sets the name of the lock file used for RewriteMap
763 synchronization</td></tr><tr><th><a href="directive-dict.html#Syntax">Syntax:
764 </a></th><td>RewriteLock <em>file-path</em></td></tr><tr><th><a href="directive-dict.html#Default">Default:
765 </a></th><td><code>None</code></td></tr><tr><th><a href="directive-dict.html#Context">Context:
766 </a></th><td>server config</td></tr><tr><th><a href="directive-dict.html#Status">Status:
767 </a></th><td>Extension</td></tr><tr><th><a href="directive-dict.html#Module">Module:
768 </a></th><td>mod_rewrite</td></tr></table>
769 <p>This directive sets the filename for a synchronization
770 lockfile which mod_rewrite needs to communicate with <code class="directive"><a href="#rewritemap">RewriteMap</a></code>
771 <em>programs</em>. Set this lockfile to a local path (not on a
772 NFS-mounted device) when you want to use a rewriting
773 map-program. It is not required for other types of rewriting
775 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div><div class="directive-section"><h2><a name="RewriteLog" id="RewriteLog">RewriteLog</a> <a name="rewritelog" id="rewritelog">Directive</a></h2><table class="directive"><tr><th><a href="directive-dict.html#Description">Description:
776 </a></th><td>Sets the name of the file used for logging rewrite engine
777 processing</td></tr><tr><th><a href="directive-dict.html#Syntax">Syntax:
778 </a></th><td>RewriteLog <em>file-path</em></td></tr><tr><th><a href="directive-dict.html#Context">Context:
779 </a></th><td>server config, virtual host</td></tr><tr><th><a href="directive-dict.html#Status">Status:
780 </a></th><td>Extension</td></tr><tr><th><a href="directive-dict.html#Module">Module:
781 </a></th><td>mod_rewrite</td></tr></table>
782 <p>The <code class="directive">RewriteLog</code> directive sets the name
783 of the file to which the server logs any rewriting actions it
784 performs. If the name does not begin with a slash
785 ('<code>/</code>') then it is assumed to be relative to the
786 <em>Server Root</em>. The directive should occur only once per
789 <div class="note"> To disable the logging of
790 rewriting actions it is not recommended to set
791 <em>Filename</em> to <code>/dev/null</code>, because
792 although the rewriting engine does not then output to a
793 logfile it still creates the logfile output internally.
794 <strong>This will slow down the server with no advantage
795 to the administrator!</strong> To disable logging either
796 remove or comment out the <code class="directive">RewriteLog</code>
797 directive or use <code>RewriteLogLevel 0</code>!
800 <div class="note"><h3>Security</h3>
802 See the <a href="../misc/security_tips.html">Apache Security Tips</a>
803 document for details on why your security could be compromised if the
804 directory where logfiles are stored is writable by anyone other than
805 the user that starts the server.
808 <div class="example"><h3>Example</h3><p><code>
809 RewriteLog "/usr/local/var/apache/logs/rewrite.log"
812 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div><div class="directive-section"><h2><a name="RewriteLogLevel" id="RewriteLogLevel">RewriteLogLevel</a> <a name="rewriteloglevel" id="rewriteloglevel">Directive</a></h2><table class="directive"><tr><th><a href="directive-dict.html#Description">Description:
813 </a></th><td>Sets the verbosity of the log file used by the rewrite
814 engine</td></tr><tr><th><a href="directive-dict.html#Syntax">Syntax:
815 </a></th><td>RewriteLogLevel <em>Level</em></td></tr><tr><th><a href="directive-dict.html#Default">Default:
816 </a></th><td><code>RerwiteLogLevel 0</code></td></tr><tr><th><a href="directive-dict.html#Context">Context:
817 </a></th><td>server config, virtual host</td></tr><tr><th><a href="directive-dict.html#Status">Status:
818 </a></th><td>Extension</td></tr><tr><th><a href="directive-dict.html#Module">Module:
819 </a></th><td>mod_rewrite</td></tr></table>
820 <p>The <code class="directive">RewriteLogLevel</code> directive sets the
821 verbosity level of the rewriting logfile. The default level 0
822 means no logging, while 9 or more means that practically all
823 actions are logged.</p>
825 <p>To disable the logging of rewriting actions simply set
826 <em>Level</em> to 0. This disables all rewrite action
829 <div class="note"> Using a high value for
830 <em>Level</em> will slow down your Apache server
831 dramatically! Use the rewriting logfile at a
832 <em>Level</em> greater than 2 only for debugging!
835 <div class="example"><h3>Example</h3><p><code>
839 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div><div class="directive-section"><h2><a name="RewriteMap" id="RewriteMap">RewriteMap</a> <a name="rewritemap" id="rewritemap">Directive</a></h2><table class="directive"><tr><th><a href="directive-dict.html#Description">Description:
840 </a></th><td>Defines a mapping function for key-lookup</td></tr><tr><th><a href="directive-dict.html#Syntax">Syntax:
841 </a></th><td>RewriteMap <em>MapName</em> <em>MapType</em>:<em>MapSource</em>
842 </td></tr><tr><th><a href="directive-dict.html#Default">Default:
843 </a></th><td><code>None</code></td></tr><tr><th><a href="directive-dict.html#Context">Context:
844 </a></th><td>server config, virtual host</td></tr><tr><th><a href="directive-dict.html#Status">Status:
845 </a></th><td>Extension</td></tr><tr><th><a href="directive-dict.html#Module">Module:
846 </a></th><td>mod_rewrite</td></tr></table>
847 <p>The <code class="directive">RewriteMap</code> directive defines a
848 <em>Rewriting Map</em> which can be used inside rule
849 substitution strings by the mapping-functions to
850 insert/substitute fields through a key lookup. The source of
851 this lookup can be of various types.</p>
853 <p>The <a id="mapfunc" name="mapfunc"><em>MapName</em></a> is
854 the name of the map and will be used to specify a
855 mapping-function for the substitution strings of a rewriting
856 rule via one of the following constructs:</p>
859 <strong><code>${</code> <em>MapName</em> <code>:</code>
860 <em>LookupKey</em> <code>}</code><br />
861 <code>${</code> <em>MapName</em> <code>:</code>
862 <em>LookupKey</em> <code>|</code> <em>DefaultValue</em>
863 <code>}</code></strong>
866 <p>When such a construct occurs the map <em>MapName</em> is
867 consulted and the key <em>LookupKey</em> is looked-up. If the
868 key is found, the map-function construct is substituted by
869 <em>SubstValue</em>. If the key is not found then it is
870 substituted by <em>DefaultValue</em> or by the empty string
871 if no <em>DefaultValue</em> was specified.</p>
873 <p>The following combinations for <em>MapType</em> and
874 <em>MapSource</em> can be used:</p>
878 <strong>Standard Plain Text</strong><br />
879 MapType: <code>txt</code>, MapSource: Unix filesystem
880 path to valid regular file
882 <p>This is the standard rewriting map feature where the
883 <em>MapSource</em> is a plain ASCII file containing
884 either blank lines, comment lines (starting with a '#'
885 character) or pairs like the following - one per
889 <strong><em>MatchingKey</em>
890 <em>SubstValue</em></strong>
893 <div class="example"><h3>Example</h3><pre>
895 ## map.txt -- rewriting map
898 Ralf.S.Engelschall rse # Bastard Operator From Hell
899 Mr.Joe.Average joe # Mr. Average
902 <div class="example"><p><code>
903 RewriteMap real-to-user txt:/path/to/file/map.txt
908 <strong>Randomized Plain Text</strong><br />
909 MapType: <code>rnd</code>, MapSource: Unix filesystem
910 path to valid regular file
912 <p>This is identical to the Standard Plain Text variant
913 above but with a special post-processing feature: After
914 looking up a value it is parsed according to contained
915 ``<code>|</code>'' characters which have the meaning of
916 ``or''. In other words they indicate a set of
917 alternatives from which the actual returned value is
918 chosen randomly. Although this sounds crazy and useless,
919 it was actually designed for load balancing in a reverse
920 proxy situation where the looked up values are server
923 <div class="example"><pre>
925 ## map.txt -- rewriting map
928 static www1|www2|www3|www4
932 <div class="example"><p><code>
933 RewriteMap servers rnd:/path/to/file/map.txt
938 <strong>Hash File</strong><br /> MapType:
939 <code>dbm[=<em>type</em>]</code>, MapSource: Unix filesystem
940 path to valid regular file
942 <p>Here the source is a binary format DBM file containing
943 the same contents as a <em>Plain Text</em> format file, but
944 in a special representation which is optimized for really
945 fast lookups. The <em>type</em> can be sdbm, gdbm, ndbm, or
946 db depending on <a href="../install.html#dbm">compile-time
947 settings</a>. If the <em>type</em> is ommitted, the
948 compile-time default will be chosen. You can create such a
949 file with any DBM tool or with the following Perl
950 script. Be sure to adjust it to create the appropriate
951 type of DBM. The example creates an NDBM file.</p>
953 <div class="example"><pre>
956 ## txt2dbm -- convert txt map to dbm format
962 ($txtmap, $dbmmap) = @ARGV;
964 open(TXT, "<$txtmap") or die "Couldn't open $txtmap!\n";
965 tie (%DB, 'NDBM_File', $dbmmap,O_RDWR|O_TRUNC|O_CREAT, 0644)
966 or die "Couldn't create $dbmmap!\n";
968 while (<TXT>) {
969 next if (/^\s*#/ or /^\s*$/);
970 $DB{$1} = $2 if (/^\s*(\S+)\s+(\S+)/);
977 <div class="example"><p><code>
978 $ txt2dbm map.txt map.db
983 <strong>Internal Function</strong><br />
984 MapType: <code>int</code>, MapSource: Internal Apache
987 <p>Here the source is an internal Apache function.
988 Currently you cannot create your own, but the following
989 functions already exists:</p>
992 <li><strong>toupper</strong>:<br />
993 Converts the looked up key to all upper case.</li>
995 <li><strong>tolower</strong>:<br />
996 Converts the looked up key to all lower case.</li>
998 <li><strong>escape</strong>:<br />
999 Translates special characters in the looked up key to
1002 <li><strong>unescape</strong>:<br />
1003 Translates hex-encodings in the looked up key back to
1004 special characters.</li>
1009 <strong>External Rewriting Program</strong><br />
1010 MapType: <code>prg</code>, MapSource: Unix filesystem
1011 path to valid regular file
1013 <p>Here the source is a program, not a map file. To
1014 create it you can use the language of your choice, but
1015 the result has to be a executable (<em>i.e.</em>, either
1016 object-code or a script with the magic cookie trick
1017 '<code>#!/path/to/interpreter</code>' as the first
1020 <p>This program is started once at startup of the Apache
1021 servers and then communicates with the rewriting engine
1022 over its <code>stdin</code> and <code>stdout</code>
1023 file-handles. For each map-function lookup it will
1024 receive the key to lookup as a newline-terminated string
1025 on <code>stdin</code>. It then has to give back the
1026 looked-up value as a newline-terminated string on
1027 <code>stdout</code> or the four-character string
1028 ``<code>NULL</code>'' if it fails (<em>i.e.</em>, there
1029 is no corresponding value for the given key). A trivial
1030 program which will implement a 1:1 map (<em>i.e.</em>,
1031 key == value) could be:</p>
1033 <div class="example"><pre>
1036 while (<STDIN>) {
1037 # ...put here any transformations or lookups...
1042 <p>But be very careful:</p>
1045 <li>``<em>Keep it simple, stupid</em>'' (KISS), because
1046 if this program hangs it will hang the Apache server
1047 when the rule occurs.</li>
1049 <li>Avoid one common mistake: never do buffered I/O on
1050 <code>stdout</code>! This will cause a deadloop! Hence
1051 the ``<code>$|=1</code>'' in the above example...</li>
1053 <li>Use the <code class="directive"><a href="#rewritelock">RewriteLock</a></code> directive to
1054 define a lockfile mod_rewrite can use to synchronize the
1055 communication to the program. By default no such
1056 synchronization takes place.</li>
1060 <p>The <code class="directive">RewriteMap</code> directive can occur more than
1061 once. For each mapping-function use one
1062 <code class="directive">RewriteMap</code> directive to declare its rewriting
1063 mapfile. While you cannot <strong>declare</strong> a map in
1064 per-directory context it is of course possible to
1065 <strong>use</strong> this map in per-directory context. </p>
1067 <div class="note"><h3>Note</h3> For plain text and DBM format files the
1068 looked-up keys are cached in-core until the <code>mtime</code> of the
1069 mapfile changes or the server does a restart. This way you can have
1070 map-functions in rules which are used for <strong>every</strong>
1071 request. This is no problem, because the external lookup only happens
1075 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div><div class="directive-section"><h2><a name="RewriteOptions" id="RewriteOptions">RewriteOptions</a> <a name="rewriteoptions" id="rewriteoptions">Directive</a></h2><table class="directive"><tr><th><a href="directive-dict.html#Description">Description:
1076 </a></th><td>Sets some special options for the rewrite engine</td></tr><tr><th><a href="directive-dict.html#Syntax">Syntax:
1077 </a></th><td>RewriteOptions <em>Options</em></td></tr><tr><th><a href="directive-dict.html#Default">Default:
1078 </a></th><td><code>None</code></td></tr><tr><th><a href="directive-dict.html#Context">Context:
1079 </a></th><td>server config, virtual host, directory, .htaccess</td></tr><tr><th><a href="directive-dict.html#Status">Status:
1080 </a></th><td>Extension</td></tr><tr><th><a href="directive-dict.html#Module">Module:
1081 </a></th><td>mod_rewrite</td></tr></table>
1083 <p>The <code class="directive">RewriteOptions</code> directive sets some
1084 special options for the current per-server or per-directory
1085 configuration. The <em>Option</em> strings can be one of the
1089 <li>'<strong><code>inherit</code></strong>'<br />
1090 This forces the current configuration to inherit the
1091 configuration of the parent. In per-virtual-server context
1092 this means that the maps, conditions and rules of the main
1093 server are inherited. In per-directory context this means
1094 that conditions and rules of the parent directory's
1095 <code>.htaccess</code> configuration are inherited.</li>
1097 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div><div class="directive-section"><h2><a name="RewriteRule" id="RewriteRule">RewriteRule</a> <a name="rewriterule" id="rewriterule">Directive</a></h2><table class="directive"><tr><th><a href="directive-dict.html#Description">Description:
1098 </a></th><td>Defines rules for the rewriting engine</td></tr><tr><th><a href="directive-dict.html#Syntax">Syntax:
1099 </a></th><td>RewriteRule
1100 <em>Pattern</em> <em>Substitution</em></td></tr><tr><th><a href="directive-dict.html#Default">Default:
1101 </a></th><td><code>None</code></td></tr><tr><th><a href="directive-dict.html#Context">Context:
1102 </a></th><td>server config, virtual host, directory, .htaccess</td></tr><tr><th><a href="directive-dict.html#Override">Override:
1103 </a></th><td>FileInfo</td></tr><tr><th><a href="directive-dict.html#Status">Status:
1104 </a></th><td>Extension</td></tr><tr><th><a href="directive-dict.html#Module">Module:
1105 </a></th><td>mod_rewrite</td></tr></table>
1106 <p>The <code class="directive">RewriteRule</code> directive is the real
1107 rewriting workhorse. The directive can occur more than once.
1108 Each directive then defines one single rewriting rule. The
1109 <strong>definition order</strong> of these rules is
1110 <strong>important</strong>, because this order is used when
1111 applying the rules at run-time.</p>
1113 <p><a id="patterns" name="patterns"><em>Pattern</em></a> can
1114 be (for Apache 1.1.x a System V8 and for Apache 1.2.x and
1115 later a POSIX) <a id="regexp" name="regexp">regular
1116 expression</a> which gets applied to the current URL. Here
1117 ``current'' means the value of the URL when this rule gets
1118 applied. This may not be the originally requested URL,
1119 because any number of rules may already have matched and made
1120 alterations to it.</p>
1122 <p>Some hints about the syntax of regular expressions:</p>
1124 <div class="note"><pre>
1125 <strong>Text:</strong>
1126 <strong><code>.</code></strong> Any single character
1127 <strong><code>[</code></strong>chars<strong><code>]</code></strong> Character class: One of chars
1128 <strong><code>[^</code></strong>chars<strong><code>]</code></strong> Character class: None of chars
1129 text1<strong><code>|</code></strong>text2 Alternative: text1 or text2
1131 <strong>Quantifiers:</strong>
1132 <strong><code>?</code></strong> 0 or 1 of the preceding text
1133 <strong><code>*</code></strong> 0 or N of the preceding text (N > 0)
1134 <strong><code>+</code></strong> 1 or N of the preceding text (N > 1)
1136 <strong>Grouping:</strong>
1137 <strong><code>(</code></strong>text<strong><code>)</code></strong> Grouping of text
1138 (either to set the borders of an alternative or
1139 for making backreferences where the <strong>N</strong>th group can
1140 be used on the RHS of a RewriteRule with <code>$</code><strong>N</strong>)
1142 <strong>Anchors:</strong>
1143 <strong><code>^</code></strong> Start of line anchor
1144 <strong><code>$</code></strong> End of line anchor
1146 <strong>Escaping:</strong>
1147 <strong><code>\</code></strong>char escape that particular char
1148 (for instance to specify the chars "<code>.[]()</code>" <em>etc.</em>)
1151 <p>For more information about regular expressions either have
1152 a look at your local regex(3) manpage or its
1153 <code>src/regex/regex.3</code> copy in the Apache 1.3
1154 distribution. If you are interested in more detailed
1155 information about regular expressions and their variants
1156 (POSIX regex, Perl regex, <em>etc.</em>) have a look at the
1157 following dedicated book on this topic:</p>
1160 <em>Mastering Regular Expressions</em><br />
1161 Jeffrey E.F. Friedl<br />
1162 Nutshell Handbook Series<br />
1163 O'Reilly & Associates, Inc. 1997<br />
1164 ISBN 1-56592-257-3<br />
1167 <p>Additionally in mod_rewrite the NOT character
1168 ('<code>!</code>') is a possible pattern prefix. This gives
1169 you the ability to negate a pattern; to say, for instance:
1170 ``<em>if the current URL does <strong>NOT</strong> match this
1171 pattern</em>''. This can be used for exceptional cases, where
1172 it is easier to match the negative pattern, or as a last
1175 <div class="note"><h3>Notice</h3>
1176 When using the NOT character
1177 to negate a pattern you cannot have grouped wildcard
1178 parts in the pattern. This is impossible because when the
1179 pattern does NOT match, there are no contents for the
1180 groups. In consequence, if negated patterns are used, you
1181 cannot use <code>$N</code> in the substitution
1185 <p><a id="rhs" name="rhs"><em>Substitution</em></a> of a
1186 rewriting rule is the string which is substituted for (or
1187 replaces) the original URL for which <em>Pattern</em>
1188 matched. Beside plain text you can use</p>
1191 <li>back-references <code>$N</code> to the RewriteRule
1194 <li>back-references <code>%N</code> to the last matched
1195 RewriteCond pattern</li>
1197 <li>server-variables as in rule condition test-strings
1198 (<code>%{VARNAME}</code>)</li>
1200 <li><a href="#mapfunc">mapping-function</a> calls
1201 (<code>${mapname:key|default}</code>)</li>
1203 <p>Back-references are <code>$</code><strong>N</strong>
1204 (<strong>N</strong>=0..9) identifiers which will be replaced
1205 by the contents of the <strong>N</strong>th group of the
1206 matched <em>Pattern</em>. The server-variables are the same
1207 as for the <em>TestString</em> of a <code>RewriteCond</code>
1208 directive. The mapping-functions come from the
1209 <code>RewriteMap</code> directive and are explained there.
1210 These three types of variables are expanded in the order of
1211 the above list. </p>
1213 <p>As already mentioned above, all the rewriting rules are
1214 applied to the <em>Substitution</em> (in the order of
1215 definition in the config file). The URL is <strong>completely
1216 replaced</strong> by the <em>Substitution</em> and the
1217 rewriting process goes on until there are no more rules
1218 unless explicitly terminated by a
1219 <code><strong>L</strong></code> flag - see below.</p>
1221 <p>There is a special substitution string named
1222 '<code>-</code>' which means: <strong>NO
1223 substitution</strong>! Sounds silly? No, it is useful to
1224 provide rewriting rules which <strong>only</strong> match
1225 some URLs but do no substitution, <em>e.g.</em>, in
1226 conjunction with the <strong>C</strong> (chain) flag to be
1227 able to have more than one pattern to be applied before a
1228 substitution occurs.</p>
1230 <p>One more note: You can even create URLs in the
1231 substitution string containing a query string part. Just use
1232 a question mark inside the substitution string to indicate
1233 that the following stuff should be re-injected into the
1234 QUERY_STRING. When you want to erase an existing query
1235 string, end the substitution string with just the question
1238 <div class="note"><h3>Note</h3>
1239 There is a special feature:
1240 When you prefix a substitution field with
1241 <code>http://</code><em>thishost</em>[<em>:thisport</em>]
1242 then <strong>mod_rewrite</strong> automatically strips it
1243 out. This auto-reduction on implicit external redirect
1244 URLs is a useful and important feature when used in
1245 combination with a mapping-function which generates the
1246 hostname part. Have a look at the first example in the
1247 example section below to understand this.
1250 <div class="note"><h3>Remember</h3>
1251 An unconditional external
1252 redirect to your own server will not work with the prefix
1253 <code>http://thishost</code> because of this feature. To
1254 achieve such a self-redirect, you have to use the
1255 <strong>R</strong>-flag (see below).
1258 <p>Additionally you can set special flags for
1259 <em>Substitution</em> by appending</p>
1262 <strong><code>[</code><em>flags</em><code>]</code></strong>
1265 as the third argument to the <code>RewriteRule</code>
1266 directive. <em>Flags</em> is a comma-separated list of the
1267 following flags: </p>
1271 '<strong><code>redirect|R</code>
1272 [=<em>code</em>]</strong>' (force <a id="redirect" name="redirect"><strong>r</strong>edirect</a>)<br />
1273 Prefix <em>Substitution</em> with
1274 <code>http://thishost[:thisport]/</code> (which makes the
1275 new URL a URI) to force a external redirection. If no
1276 <em>code</em> is given a HTTP response of 302 (MOVED
1277 TEMPORARILY) is used. If you want to use other response
1278 codes in the range 300-400 just specify them as a number
1279 or use one of the following symbolic names:
1280 <code>temp</code> (default), <code>permanent</code>,
1281 <code>seeother</code>. Use it for rules which should
1282 canonicalize the URL and give it back to the client,
1283 <em>e.g.</em>, translate ``<code>/~</code>'' into
1284 ``<code>/u/</code>'' or always append a slash to
1285 <code>/u/</code><em>user</em>, etc.<br />
1288 <p><strong>Note:</strong> When you use this flag, make
1289 sure that the substitution field is a valid URL! If not,
1290 you are redirecting to an invalid location! And remember
1291 that this flag itself only prefixes the URL with
1292 <code>http://thishost[:thisport]/</code>, rewriting
1293 continues. Usually you also want to stop and do the
1294 redirection immediately. To stop the rewriting you also
1295 have to provide the 'L' flag.</p>
1298 <li>'<strong><code>forbidden|F</code></strong>' (force URL
1299 to be <strong>f</strong>orbidden)<br />
1300 This forces the current URL to be forbidden,
1301 <em>i.e.</em>, it immediately sends back a HTTP response of
1302 403 (FORBIDDEN). Use this flag in conjunction with
1303 appropriate RewriteConds to conditionally block some
1306 <li>'<strong><code>gone|G</code></strong>' (force URL to be
1307 <strong>g</strong>one)<br />
1308 This forces the current URL to be gone, <em>i.e.</em>, it
1309 immediately sends back a HTTP response of 410 (GONE). Use
1310 this flag to mark pages which no longer exist as gone.</li>
1313 '<strong><code>proxy|P</code></strong>' (force
1314 <strong>p</strong>roxy)<br />
1315 This flag forces the substitution part to be internally
1316 forced as a proxy request and immediately (<em>i.e.</em>,
1317 rewriting rule processing stops here) put through the <a href="mod_proxy.html">proxy module</a>. You have to make
1318 sure that the substitution string is a valid URI
1319 (<em>e.g.</em>, typically starting with
1320 <code>http://</code><em>hostname</em>) which can be
1321 handled by the Apache proxy module. If not you get an
1322 error from the proxy module. Use this flag to achieve a
1323 more powerful implementation of the <a href="mod_proxy.html#proxypass">ProxyPass</a> directive,
1324 to map some remote stuff into the namespace of the local
1327 <p>Notice: To use this functionality make sure you have
1328 the proxy module compiled into your Apache server
1329 program. If you don't know please check whether
1330 <code>mod_proxy.c</code> is part of the ``<code>httpd
1331 -l</code>'' output. If yes, this functionality is
1332 available to mod_rewrite. If not, then you first have to
1333 rebuild the ``<code>httpd</code>'' program with mod_proxy
1337 <li>'<strong><code>last|L</code></strong>'
1338 (<strong>l</strong>ast rule)<br />
1339 Stop the rewriting process here and don't apply any more
1340 rewriting rules. This corresponds to the Perl
1341 <code>last</code> command or the <code>break</code> command
1342 from the C language. Use this flag to prevent the currently
1343 rewritten URL from being rewritten further by following
1344 rules. For example, use it to rewrite the root-path URL
1345 ('<code>/</code>') to a real one, <em>e.g.</em>,
1346 '<code>/e/www/</code>'.</li>
1348 <li>'<strong><code>next|N</code></strong>'
1349 (<strong>n</strong>ext round)<br />
1350 Re-run the rewriting process (starting again with the
1351 first rewriting rule). Here the URL to match is again not
1352 the original URL but the URL from the last rewriting rule.
1353 This corresponds to the Perl <code>next</code> command or
1354 the <code>continue</code> command from the C language. Use
1355 this flag to restart the rewriting process, <em>i.e.</em>,
1356 to immediately go to the top of the loop.<br />
1357 <strong>But be careful not to create an infinite
1360 <li>'<strong><code>chain|C</code></strong>'
1361 (<strong>c</strong>hained with next rule)<br />
1362 This flag chains the current rule with the next rule
1363 (which itself can be chained with the following rule,
1364 <em>etc.</em>). This has the following effect: if a rule
1365 matches, then processing continues as usual, <em>i.e.</em>,
1366 the flag has no effect. If the rule does
1367 <strong>not</strong> match, then all following chained
1368 rules are skipped. For instance, use it to remove the
1369 ``<code>.www</code>'' part inside a per-directory rule set
1370 when you let an external redirect happen (where the
1371 ``<code>.www</code>'' part should not to occur!).</li>
1374 '<strong><code>type|T</code></strong>=<em>MIME-type</em>'
1375 (force MIME <strong>t</strong>ype)<br />
1376 Force the MIME-type of the target file to be
1377 <em>MIME-type</em>. For instance, this can be used to
1378 simulate the <code>mod_alias</code> directive
1379 <code>ScriptAlias</code> which internally forces all files
1380 inside the mapped directory to have a MIME type of
1381 ``<code>application/x-httpd-cgi</code>''.</li>
1384 '<strong><code>nosubreq|NS</code></strong>' (used only if
1385 <strong>n</strong>o internal
1386 <strong>s</strong>ub-request)<br />
1387 This flag forces the rewriting engine to skip a
1388 rewriting rule if the current request is an internal
1389 sub-request. For instance, sub-requests occur internally
1390 in Apache when <code>mod_include</code> tries to find out
1391 information about possible directory default files
1392 (<code>index.xxx</code>). On sub-requests it is not
1393 always useful and even sometimes causes a failure to if
1394 the complete set of rules are applied. Use this flag to
1395 exclude some rules.<br />
1398 <p>Use the following rule for your decision: whenever you
1399 prefix some URLs with CGI-scripts to force them to be
1400 processed by the CGI-script, the chance is high that you
1401 will run into problems (or even overhead) on
1402 sub-requests. In these cases, use this flag.</p>
1405 <li>'<strong><code>nocase|NC</code></strong>'
1406 (<strong>n</strong>o <strong>c</strong>ase)<br />
1407 This makes the <em>Pattern</em> case-insensitive,
1408 <em>i.e.</em>, there is no difference between 'A-Z' and
1409 'a-z' when <em>Pattern</em> is matched against the current
1412 <li>'<strong><code>qsappend|QSA</code></strong>'
1413 (<strong>q</strong>uery <strong>s</strong>tring
1414 <strong>a</strong>ppend)<br />
1415 This flag forces the rewriting engine to append a query
1416 string part in the substitution string to the existing one
1417 instead of replacing it. Use this when you want to add more
1418 data to the query string via a rewrite rule.</li>
1421 '<strong><code>noescape|NE</code></strong>'
1422 (<strong>n</strong>o URI <strong>e</strong>scaping of
1424 This flag keeps mod_rewrite from applying the usual URI
1425 escaping rules to the result of a rewrite. Ordinarily,
1426 special characters (such as '%', '$', ';', and so on)
1427 will be escaped into their hexcode equivalents ('%25',
1428 '%24', and '%3B', respectively); this flag prevents this
1429 from being done. This allows percent symbols to appear in
1431 <div class="example"><p><code>
1432 RewriteRule /foo/(.*) /bar?arg=P1\%3d$1 [R,NE]
1435 which would turn '<code>/foo/zed</code>' into a safe
1436 request for '<code>/bar?arg=P1=zed</code>'.
1440 '<strong><code>passthrough|PT</code></strong>'
1441 (<strong>p</strong>ass <strong>t</strong>hrough to next
1443 This flag forces the rewriting engine to set the
1444 <code>uri</code> field of the internal
1445 <code>request_rec</code> structure to the value of the
1446 <code>filename</code> field. This flag is just a hack to
1447 be able to post-process the output of
1448 <code>RewriteRule</code> directives by
1449 <code>Alias</code>, <code>ScriptAlias</code>,
1450 <code>Redirect</code>, <em>etc.</em> directives from
1451 other URI-to-filename translators. A trivial example to
1452 show the semantics: If you want to rewrite
1453 <code>/abc</code> to <code>/def</code> via the rewriting
1454 engine of <code>mod_rewrite</code> and then
1455 <code>/def</code> to <code>/ghi</code> with
1456 <code>mod_alias</code>:
1457 <div class="example"><p><code>
1458 RewriteRule ^/abc(.*) /def$1 [PT]<br />
1461 If you omit the <code>PT</code> flag then
1462 <code>mod_rewrite</code> will do its job fine,
1463 <em>i.e.</em>, it rewrites <code>uri=/abc/...</code> to
1464 <code>filename=/def/...</code> as a full API-compliant
1465 URI-to-filename translator should do. Then
1466 <code>mod_alias</code> comes and tries to do a
1467 URI-to-filename transition which will not work.
1469 <p>Note: <strong>You have to use this flag if you want to
1470 intermix directives of different modules which contain
1471 URL-to-filename translators</strong>. The typical example
1472 is the use of <code>mod_alias</code> and
1473 <code>mod_rewrite</code>..</p>
1475 <div class="note"><h3>For Apache hackers</h3>
1476 If the current Apache API had a filename-to-filename
1477 hook additionally to the URI-to-filename hook then we
1478 wouldn't need this flag! But without such a hook this
1479 flag is the only solution. The Apache Group has
1480 discussed this problem and will add such a hook in
1485 <li>'<strong><code>skip|S</code></strong>=<em>num</em>'
1486 (<strong>s</strong>kip next rule(s))<br />
1487 This flag forces the rewriting engine to skip the next
1488 <em>num</em> rules in sequence when the current rule
1489 matches. Use this to make pseudo if-then-else constructs:
1490 The last rule of the then-clause becomes
1491 <code>skip=N</code> where N is the number of rules in the
1492 else-clause. (This is <strong>not</strong> the same as the
1493 'chain|C' flag!)</li>
1496 '<strong><code>env|E=</code></strong><em>VAR</em>:<em>VAL</em>'
1497 (set <strong>e</strong>nvironment variable)<br />
1498 This forces an environment variable named <em>VAR</em> to
1499 be set to the value <em>VAL</em>, where <em>VAL</em> can
1500 contain regexp backreferences <code>$N</code> and
1501 <code>%N</code> which will be expanded. You can use this
1502 flag more than once to set more than one variable. The
1503 variables can be later dereferenced in many situations, but
1504 usually from within XSSI (via <code><!--#echo
1505 var="VAR"--></code>) or CGI (<em>e.g.</em>
1506 <code>$ENV{'VAR'}</code>). Additionally you can dereference
1507 it in a following RewriteCond pattern via
1508 <code>%{ENV:VAR}</code>. Use this to strip but remember
1509 information from URLs.</li>
1512 '<strong><code>cookie|CO=</code></strong><em>NAME</em>:<em>VAL</em>:<em>domain</em>[:<em>lifetime</em>[:<em>path</em>]]'
1513 (set <strong>co</strong>cookie)<br />
1514 This sets a cookie on the client's browser. The cookie's name
1515 is specified by <em>NAME</em> and the value is
1516 <em>VAL</em>. The <em>domain</em> field is the domain of the
1517 cookie, such as '.apache.org',the optional <em>lifetime</em>
1518 is the lifetime of the cookie in minutes, and the optional
1519 <em>path</em> is the path of the cookie</li>
1523 <div class="note"><h3>Note</h3> Never forget that <em>Pattern</em> is
1524 applied to a complete URL in per-server configuration
1525 files. <strong>But in per-directory configuration files, the
1526 per-directory prefix (which always is the same for a specific
1527 directory!) is automatically <em>removed</em> for the pattern matching
1528 and automatically <em>added</em> after the substitution has been
1529 done.</strong> This feature is essential for many sorts of rewriting,
1530 because without this prefix stripping you have to match the parent
1531 directory which is not always possible.
1533 <p>There is one exception: If a substitution string
1534 starts with ``<code>http://</code>'' then the directory
1535 prefix will <strong>not</strong> be added and an
1536 external redirect or proxy throughput (if flag
1537 <strong>P</strong> is used!) is forced!</p>
1540 <div class="note"><h3>Note</h3>
1541 To enable the rewriting engine
1542 for per-directory configuration files you need to set
1543 ``<code>RewriteEngine On</code>'' in these files
1544 <strong>and</strong> ``<code>Options
1545 FollowSymLinks</code>'' must be enabled. If your
1546 administrator has disabled override of
1547 <code>FollowSymLinks</code> for a user's directory, then
1548 you cannot use the rewriting engine. This restriction is
1549 needed for security reasons.
1552 <p>Here are all possible substitution combinations and their
1555 <p><strong>Inside per-server configuration
1556 (<code>httpd.conf</code>)<br />
1557 for request ``<code>GET
1558 /somepath/pathinfo</code>'':</strong><br />
1561 <div class="note"><pre>
1562 <strong>Given Rule</strong> <strong>Resulting Substitution</strong>
1563 ---------------------------------------------- ----------------------------------
1564 ^/somepath(.*) otherpath$1 not supported, because invalid!
1566 ^/somepath(.*) otherpath$1 [R] not supported, because invalid!
1568 ^/somepath(.*) otherpath$1 [P] not supported, because invalid!
1569 ---------------------------------------------- ----------------------------------
1570 ^/somepath(.*) /otherpath$1 /otherpath/pathinfo
1572 ^/somepath(.*) /otherpath$1 [R] http://thishost/otherpath/pathinfo
1573 via external redirection
1575 ^/somepath(.*) /otherpath$1 [P] not supported, because silly!
1576 ---------------------------------------------- ----------------------------------
1577 ^/somepath(.*) http://thishost/otherpath$1 /otherpath/pathinfo
1579 ^/somepath(.*) http://thishost/otherpath$1 [R] http://thishost/otherpath/pathinfo
1580 via external redirection
1582 ^/somepath(.*) http://thishost/otherpath$1 [P] not supported, because silly!
1583 ---------------------------------------------- ----------------------------------
1584 ^/somepath(.*) http://otherhost/otherpath$1 http://otherhost/otherpath/pathinfo
1585 via external redirection
1587 ^/somepath(.*) http://otherhost/otherpath$1 [R] http://otherhost/otherpath/pathinfo
1588 via external redirection
1589 (the [R] flag is redundant)
1591 ^/somepath(.*) http://otherhost/otherpath$1 [P] http://otherhost/otherpath/pathinfo
1595 <p><strong>Inside per-directory configuration for
1596 <code>/somepath</code><br />
1597 (<em>i.e.</em>, file <code>.htaccess</code> in dir
1598 <code>/physical/path/to/somepath</code> containing
1599 <code>RewriteBase /somepath</code>)<br />
1600 for request ``<code>GET
1601 /somepath/localpath/pathinfo</code>'':</strong><br />
1604 <div class="note"><pre>
1605 <strong>Given Rule</strong> <strong>Resulting Substitution</strong>
1606 ---------------------------------------------- ----------------------------------
1607 ^localpath(.*) otherpath$1 /somepath/otherpath/pathinfo
1609 ^localpath(.*) otherpath$1 [R] http://thishost/somepath/otherpath/pathinfo
1610 via external redirection
1612 ^localpath(.*) otherpath$1 [P] not supported, because silly!
1613 ---------------------------------------------- ----------------------------------
1614 ^localpath(.*) /otherpath$1 /otherpath/pathinfo
1616 ^localpath(.*) /otherpath$1 [R] http://thishost/otherpath/pathinfo
1617 via external redirection
1619 ^localpath(.*) /otherpath$1 [P] not supported, because silly!
1620 ---------------------------------------------- ----------------------------------
1621 ^localpath(.*) http://thishost/otherpath$1 /otherpath/pathinfo
1623 ^localpath(.*) http://thishost/otherpath$1 [R] http://thishost/otherpath/pathinfo
1624 via external redirection
1626 ^localpath(.*) http://thishost/otherpath$1 [P] not supported, because silly!
1627 ---------------------------------------------- ----------------------------------
1628 ^localpath(.*) http://otherhost/otherpath$1 http://otherhost/otherpath/pathinfo
1629 via external redirection
1631 ^localpath(.*) http://otherhost/otherpath$1 [R] http://otherhost/otherpath/pathinfo
1632 via external redirection
1633 (the [R] flag is redundant)
1635 ^localpath(.*) http://otherhost/otherpath$1 [P] http://otherhost/otherpath/pathinfo
1639 <p><strong>Example:</strong></p>
1641 <p>We want to rewrite URLs of the form </p>
1644 <code>/</code> <em>Language</em> <code>/~</code>
1645 <em>Realname</em> <code>/.../</code> <em>File</em>
1651 <code>/u/</code> <em>Username</em> <code>/.../</code>
1652 <em>File</em> <code>.</code> <em>Language</em>
1655 <p>We take the rewrite mapfile from above and save it under
1656 <code>/path/to/file/map.txt</code>. Then we only have to
1657 add the following lines to the Apache server configuration
1660 <div class="example"><pre>
1661 RewriteLog /path/to/file/rewrite.log
1662 RewriteMap real-to-user txt:/path/to/file/map.txt
1663 RewriteRule ^/([^/]+)/~([^/]+)/(.*)$ /u/${real-to-user:$2|nobody}/$3.$1
1665 </div></div><div id="footer"><p class="apache">Maintained by the <a href="http://httpd.apache.org/docs-project/">Apache HTTP Server Documentation Project</a></p><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></body></html>