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
8 <title>mod_rewrite - Apache HTTP Server</title>
9 <link href="../style/css/manual.css" rel="stylesheet" media="all" type="text/css" title="Main stylesheet" />
10 <link href="../style/css/manual-loose-100pc.css" rel="alternate stylesheet" media="all" type="text/css" title="No Sidebar - Default font size" />
11 <link href="../style/css/manual-print.css" rel="stylesheet" media="print" type="text/css" />
12 <link href="../images/favicon.ico" rel="shortcut icon" /></head>
14 <div id="page-header">
15 <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>
16 <p class="apache">Apache HTTP Server Version 2.1</p>
17 <img alt="" src="../images/feather.gif" /></div>
18 <div class="up"><a href="./"><img title="<-" alt="<-" src="../images/left.gif" /></a></div>
20 <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.1</a> > <a href="./">Modules</a></div>
21 <div id="page-content">
22 <div id="preamble"><h1>Apache Module mod_rewrite</h1>
24 <p><span>Available Languages: </span><a href="../en/mod/mod_rewrite.html" title="English"> en </a></p>
26 <table class="module"><tr><th><a href="module-dict.html#Description">Description:</a></th><td>Provides a rule-based rewriting engine to rewrite requested
27 URLs on the fly</td></tr>
28 <tr><th><a href="module-dict.html#Status">Status:</a></th><td>Extension</td></tr>
29 <tr><th><a href="module-dict.html#ModuleIdentifier">Module Identifier:</a></th><td>rewrite_module</td></tr>
30 <tr><th><a href="module-dict.html#SourceFile">Source File:</a></th><td>mod_rewrite.c</td></tr>
31 <tr><th><a href="module-dict.html#Compatibility">Compatibility:</a></th><td>Available in Apache 1.3 and later</td></tr></table>
35 <p>``The great thing about mod_rewrite is it gives you
36 all the configurability and flexibility of Sendmail.
37 The downside to mod_rewrite is that it gives you all
38 the configurability and flexibility of Sendmail.''</p>
40 <p class="cite">-- <cite>Brian Behlendorf</cite><br />
46 <p>`` Despite the tons of examples and docs,
47 mod_rewrite is voodoo. Damned cool voodoo, but still
50 <p class="cite">-- <cite>Brian Moore</cite><br />
56 <p>Welcome to mod_rewrite, the Swiss Army Knife of URL
59 <p>This module uses a rule-based rewriting engine (based on a
60 regular-expression parser) to rewrite requested URLs on the
61 fly. It supports an unlimited number of rules and an
62 unlimited number of attached rule conditions for each rule to
63 provide a really flexible and powerful URL manipulation
64 mechanism. The URL manipulations can depend on various tests,
65 for instance server variables, environment variables, HTTP
66 headers, time stamps and even external database lookups in
67 various formats can be used to achieve a really granular URL
70 <p>This module operates on the full URLs (including the
71 path-info part) both in per-server context
72 (<code>httpd.conf</code>) and per-directory context
73 (<code>.htaccess</code>) and can even generate query-string
74 parts on result. The rewritten result can lead to internal
75 sub-processing, external request redirection or even to an
76 internal proxy throughput.</p>
78 <p>But all this functionality and flexibility has its
79 drawback: complexity. So don't expect to understand this
80 entire module in just one day.</p>
82 <p>This module was invented and originally written in April
83 1996 and gifted exclusively to the The Apache Group in July 1997
87 <a href="http://www.engelschall.com/"><code>Ralf S.
88 Engelschall</code></a><br />
89 <a href="mailto:rse@engelschall.com"><code>rse@engelschall.com</code></a><br />
90 <a href="http://www.engelschall.com/"><code>www.engelschall.com</code></a>
93 <div id="quickview"><h3 class="directives">Directives</h3>
95 <li><img alt="" src="../images/down.gif" /> <a href="#rewritebase">RewriteBase</a></li>
96 <li><img alt="" src="../images/down.gif" /> <a href="#rewritecond">RewriteCond</a></li>
97 <li><img alt="" src="../images/down.gif" /> <a href="#rewriteengine">RewriteEngine</a></li>
98 <li><img alt="" src="../images/down.gif" /> <a href="#rewritelock">RewriteLock</a></li>
99 <li><img alt="" src="../images/down.gif" /> <a href="#rewritelog">RewriteLog</a></li>
100 <li><img alt="" src="../images/down.gif" /> <a href="#rewriteloglevel">RewriteLogLevel</a></li>
101 <li><img alt="" src="../images/down.gif" /> <a href="#rewritemap">RewriteMap</a></li>
102 <li><img alt="" src="../images/down.gif" /> <a href="#rewriteoptions">RewriteOptions</a></li>
103 <li><img alt="" src="../images/down.gif" /> <a href="#rewriterule">RewriteRule</a></li>
107 <li><img alt="" src="../images/down.gif" /> <a href="#Internal">Internal Processing</a></li>
108 <li><img alt="" src="../images/down.gif" /> <a href="#EnvVar">Environment Variables</a></li>
109 <li><img alt="" src="../images/down.gif" /> <a href="#Solutions">Practical Solutions</a></li>
111 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
112 <div class="section">
113 <h2><a name="Internal" id="Internal">Internal Processing</a></h2>
115 <p>The internal processing of this module is very complex but
116 needs to be explained once even to the average user to avoid
117 common mistakes and to let you exploit its full
120 <h3><a name="InternalAPI" id="InternalAPI">API Phases</a></h3>
122 <p>First you have to understand that when Apache processes a
123 HTTP request it does this in phases. A hook for each of these
124 phases is provided by the Apache API. Mod_rewrite uses two of
125 these hooks: the URL-to-filename translation hook which is
126 used after the HTTP request has been read but before any
127 authorization starts and the Fixup hook which is triggered
128 after the authorization phases and after the per-directory
129 config files (<code>.htaccess</code>) have been read, but
130 before the content handler is activated.</p>
132 <p>So, after a request comes in and Apache has determined the
133 corresponding server (or virtual server) the rewriting engine
134 starts processing of all mod_rewrite directives from the
135 per-server configuration in the URL-to-filename phase. A few
136 steps later when the final data directories are found, the
137 per-directory configuration directives of mod_rewrite are
138 triggered in the Fixup phase. In both situations mod_rewrite
139 rewrites URLs either to new URLs or to filenames, although
140 there is no obvious distinction between them. This is a usage
141 of the API which was not intended to be this way when the API
142 was designed, but as of Apache 1.x this is the only way
143 mod_rewrite can operate. To make this point more clear
144 remember the following two points:</p>
147 <li>Although mod_rewrite rewrites URLs to URLs, URLs to
148 filenames and even filenames to filenames, the API
149 currently provides only a URL-to-filename hook. In Apache
150 2.0 the two missing hooks will be added to make the
151 processing more clear. But this point has no drawbacks for
152 the user, it is just a fact which should be remembered:
153 Apache does more in the URL-to-filename hook than the API
157 Unbelievably mod_rewrite provides URL manipulations in
158 per-directory context, <em>i.e.</em>, within
159 <code>.htaccess</code> files, although these are reached
160 a very long time after the URLs have been translated to
161 filenames. It has to be this way because
162 <code>.htaccess</code> files live in the filesystem, so
163 processing has already reached this stage. In other
164 words: According to the API phases at this time it is too
165 late for any URL manipulations. To overcome this chicken
166 and egg problem mod_rewrite uses a trick: When you
167 manipulate a URL/filename in per-directory context
168 mod_rewrite first rewrites the filename back to its
169 corresponding URL (which is usually impossible, but see
170 the <code>RewriteBase</code> directive below for the
171 trick to achieve this) and then initiates a new internal
172 sub-request with the new URL. This restarts processing of
175 <p>Again mod_rewrite tries hard to make this complicated
176 step totally transparent to the user, but you should
177 remember here: While URL manipulations in per-server
178 context are really fast and efficient, per-directory
179 rewrites are slow and inefficient due to this chicken and
180 egg problem. But on the other hand this is the only way
181 mod_rewrite can provide (locally restricted) URL
182 manipulations to the average user.</p>
186 <p>Don't forget these two points!</p>
189 <h3><a name="InternalRuleset" id="InternalRuleset">Ruleset Processing</a></h3>
191 <p>Now when mod_rewrite is triggered in these two API phases, it
192 reads the configured rulesets from its configuration
193 structure (which itself was either created on startup for
194 per-server context or during the directory walk of the Apache
195 kernel for per-directory context). Then the URL rewriting
196 engine is started with the contained ruleset (one or more
197 rules together with their conditions). The operation of the
198 URL rewriting engine itself is exactly the same for both
199 configuration contexts. Only the final result processing is
202 <p>The order of rules in the ruleset is important because the
203 rewriting engine processes them in a special (and not very
204 obvious) order. The rule is this: The rewriting engine loops
205 through the ruleset rule by rule (<code class="directive"><a href="#rewriterule">RewriteRule</a></code> directives) and
206 when a particular rule matches it optionally loops through
207 existing corresponding conditions (<code>RewriteCond</code>
208 directives). For historical reasons the conditions are given
209 first, and so the control flow is a little bit long-winded. See
210 Figure 1 for more details.</p>
212 <img src="../images/mod_rewrite_fig1.gif" width="428" height="385" alt="[Needs graphics capability to display]" /><br />
213 <dfn>Figure 1:</dfn>The control flow through the rewriting ruleset
215 <p>As you can see, first the URL is matched against the
216 <em>Pattern</em> of each rule. When it fails mod_rewrite
217 immediately stops processing this rule and continues with the
218 next rule. If the <em>Pattern</em> matches, mod_rewrite looks
219 for corresponding rule conditions. If none are present, it
220 just substitutes the URL with a new value which is
221 constructed from the string <em>Substitution</em> and goes on
222 with its rule-looping. But if conditions exist, it starts an
223 inner loop for processing them in the order that they are
224 listed. For conditions the logic is different: we don't match
225 a pattern against the current URL. Instead we first create a
226 string <em>TestString</em> by expanding variables,
227 back-references, map lookups, <em>etc.</em> and then we try
228 to match <em>CondPattern</em> against it. If the pattern
229 doesn't match, the complete set of conditions and the
230 corresponding rule fails. If the pattern matches, then the
231 next condition is processed until no more conditions are
232 available. If all conditions match, processing is continued
233 with the substitution of the URL with
234 <em>Substitution</em>.</p>
238 <h3><a name="quoting" id="quoting">Quoting Special Characters</a></h3>
240 <p>As of Apache 1.3.20, special characters in
241 <em>TestString</em> and <em>Substitution</em> strings can be
242 escaped (that is, treated as normal characters without their
243 usual special meaning) by prefixing them with a slosh ('\')
244 character. In other words, you can include an actual
245 dollar-sign character in a <em>Substitution</em> string by
246 using '<code>\$</code>'; this keeps mod_rewrite from trying
247 to treat it as a backreference.</p>
250 <h3><a name="InternalBackRefs" id="InternalBackRefs">Regex Back-Reference Availability</a></h3>
252 <p>One important thing here has to be remembered: Whenever you
253 use parentheses in <em>Pattern</em> or in one of the
254 <em>CondPattern</em>, back-references are internally created
255 which can be used with the strings <code>$N</code> and
256 <code>%N</code> (see below). These are available for creating
257 the strings <em>Substitution</em> and <em>TestString</em>.
258 Figure 2 shows to which locations the back-references are
259 transfered for expansion.</p>
262 <img src="../images/mod_rewrite_fig2.gif" width="381" height="179" alt="[Needs graphics capability to display]" /><br />
263 <dfn>Figure 2:</dfn> The back-reference flow through a rule.
265 <p>We know this was a crash course on mod_rewrite's internal
266 processing. But you will benefit from this knowledge when
267 reading the following documentation of the available
271 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
272 <div class="section">
273 <h2><a name="EnvVar" id="EnvVar">Environment Variables</a></h2>
275 <p>This module keeps track of two additional (non-standard)
276 CGI/SSI environment variables named <code>SCRIPT_URL</code>
277 and <code>SCRIPT_URI</code>. These contain the
278 <em>logical</em> Web-view to the current resource, while the
279 standard CGI/SSI variables <code>SCRIPT_NAME</code> and
280 <code>SCRIPT_FILENAME</code> contain the <em>physical</em>
283 <p>Notice: These variables hold the URI/URL <em>as they were
284 initially requested</em>, <em>i.e.</em>, <em>before</em> any
285 rewriting. This is important because the rewriting process is
286 primarily used to rewrite logical URLs to physical
289 <div class="example"><h3>Example</h3><pre>
290 SCRIPT_NAME=/sw/lib/w3s/tree/global/u/rse/.www/index.html
291 SCRIPT_FILENAME=/u/rse/.www/index.html
293 SCRIPT_URI=http://en1.engelschall.com/u/rse/
296 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
297 <div class="section">
298 <h2><a name="Solutions" id="Solutions">Practical Solutions</a></h2>
300 <p>We also have an <a href="../misc/rewriteguide.html">URL
301 Rewriting Guide</a> available, which provides a collection of
302 practical solutions for URL-based problems. There you can
303 find real-life rulesets and additional information about
306 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
307 <div class="directive-section"><h2><a name="RewriteBase" id="RewriteBase">RewriteBase</a> <a name="rewritebase" id="rewritebase">Directive</a></h2>
308 <table class="directive">
309 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Sets the base URL for per-directory rewrites</td></tr>
310 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>RewriteBase <em>URL-path</em></code></td></tr>
311 <tr><th><a href="directive-dict.html#Default">Default:</a></th><td><code>See usage for information.</code></td></tr>
312 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>directory, .htaccess</td></tr>
313 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>FileInfo</td></tr>
314 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Extension</td></tr>
315 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_rewrite</td></tr>
317 <p>The <code class="directive">RewriteBase</code> directive explicitly
318 sets the base URL for per-directory rewrites. As you will see
319 below, <code class="directive"><a href="#rewriterule">RewriteRule</a></code>
320 can be used in per-directory config files
321 (<code>.htaccess</code>). There it will act locally,
322 <em>i.e.</em>, the local directory prefix is stripped at this
323 stage of processing and your rewriting rules act only on the
324 remainder. At the end it is automatically added back to the
325 path. The default setting is; <code class="directive">RewriteBase</code> <em>physical-directory-path</em></p>
327 <p>When a substitution occurs for a new URL, this module has
328 to re-inject the URL into the server processing. To be able
329 to do this it needs to know what the corresponding URL-prefix
330 or URL-base is. By default this prefix is the corresponding
331 filepath itself. <strong>But at most websites URLs are NOT
332 directly related to physical filename paths, so this
333 assumption will usually be wrong!</strong> There you have to
334 use the <code>RewriteBase</code> directive to specify the
335 correct URL-prefix.</p>
337 <div class="note"> If your webserver's URLs are <strong>not</strong> directly
338 related to physical file paths, you have to use
339 <code class="directive">RewriteBase</code> in every <code>.htaccess</code>
340 files where you want to use <code class="directive"><a href="#rewriterule">RewriteRule</a></code> directives.
343 <p> For example, assume the following per-directory config file:</p>
345 <div class="example"><pre>
347 # /abc/def/.htaccess -- per-dir config file for directory /abc/def
348 # Remember: /abc/def is the physical path of /xyz, <em>i.e.</em>, the server
349 # has a 'Alias /xyz /abc/def' directive <em>e.g.</em>
354 # let the server know that we were reached via /xyz and not
355 # via the physical path prefix /abc/def
358 # now the rewriting rules
359 RewriteRule ^oldstuff\.html$ newstuff.html
362 <p>In the above example, a request to
363 <code>/xyz/oldstuff.html</code> gets correctly rewritten to
364 the physical file <code>/abc/def/newstuff.html</code>.</p>
366 <div class="note"><h3>For Apache Hackers</h3>
367 <p>The following list gives detailed information about
368 the internal processing steps:</p>
374 /xyz/oldstuff.html -> /abc/def/oldstuff.html (per-server Alias)
375 /abc/def/oldstuff.html -> /abc/def/newstuff.html (per-dir RewriteRule)
376 /abc/def/newstuff.html -> /xyz/newstuff.html (per-dir RewriteBase)
377 /xyz/newstuff.html -> /abc/def/newstuff.html (per-server Alias)
380 /abc/def/newstuff.html
382 <p>This seems very complicated but is
383 the correct Apache internal processing, because the
384 per-directory rewriting comes too late in the
385 process. So, when it occurs the (rewritten) request
386 has to be re-injected into the Apache kernel! BUT:
387 While this seems like a serious overhead, it really
388 isn't, because this re-injection happens fully
389 internally to the Apache server and the same
390 procedure is used by many other operations inside
391 Apache. So, you can be sure the design and
392 implementation is correct.</p>
397 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
398 <div class="directive-section"><h2><a name="RewriteCond" id="RewriteCond">RewriteCond</a> <a name="rewritecond" id="rewritecond">Directive</a></h2>
399 <table class="directive">
400 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Defines a condition under which rewriting will take place
402 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code> RewriteCond
403 <em>TestString</em> <em>CondPattern</em></code></td></tr>
404 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
405 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>FileInfo</td></tr>
406 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Extension</td></tr>
407 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_rewrite</td></tr>
409 <p>The <code class="directive">RewriteCond</code> directive defines a
410 rule condition. Precede a <code class="directive"><a href="#rewriterule">RewriteRule</a></code> directive with one
411 or more <code class="directive">RewriteCond</code> directives. The following
412 rewriting rule is only used if its pattern matches the current
413 state of the URI <strong>and</strong> if these additional
414 conditions apply too.</p>
416 <p><em>TestString</em> is a string which can contains the
417 following expanded constructs in addition to plain text:</p>
421 <strong>RewriteRule backreferences</strong>: These are
422 backreferences of the form
425 <strong><code>$N</code></strong>
427 (0 <= N <= 9) which provide access to the grouped
428 parts (parenthesis!) of the pattern from the
429 corresponding <code>RewriteRule</code> directive (the one
430 following the current bunch of <code>RewriteCond</code>
435 <strong>RewriteCond backreferences</strong>: These are
436 backreferences of the form
439 <strong><code>%N</code></strong>
441 (1 <= N <= 9) which provide access to the grouped
442 parts (parentheses!) of the pattern from the last matched
443 <code>RewriteCond</code> directive in the current bunch
448 <strong>RewriteMap expansions</strong>: These are
449 expansions of the form
452 <strong><code>${mapname:key|default}</code></strong>
454 See <a href="#mapfunc">the documentation for
455 RewriteMap</a> for more details.
459 <strong>Server-Variables</strong>: These are variables of
463 <strong><code>%{</code> <em>NAME_OF_VARIABLE</em>
464 <code>}</code></strong>
466 where <em>NAME_OF_VARIABLE</em> can be a string taken
467 from the following list:
471 <th>HTTP headers:</th> <th>connection & request:</th> <th />
476 HTTP_USER_AGENT<br />
481 HTTP_PROXY_CONNECTION<br />
491 SCRIPT_FILENAME<br />
501 <th>server internals:</th> <th>system stuff:</th> <th>specials:</th>
511 SERVER_PROTOCOL<br />
512 SERVER_SOFTWARE<br />
530 REQUEST_FILENAME<br />
537 <p>These variables all
538 correspond to the similarly named HTTP
539 MIME-headers, C variables of the Apache server or
540 <code>struct tm</code> fields of the Unix system.
541 Most are documented elsewhere in the Manual or in
542 the CGI specification. Those that are special to
543 mod_rewrite include:</p>
546 <dt><code>IS_SUBREQ</code></dt>
548 <dd>Will contain the text "true" if the request
549 currently being processed is a sub-request,
550 "false" otherwise. Sub-requests may be generated
551 by modules that need to resolve additional files
552 or URIs in order to complete their tasks.</dd>
554 <dt><code>API_VERSION</code></dt>
556 <dd>This is the version of the Apache module API
557 (the internal interface between server and
558 module) in the current httpd build, as defined in
559 include/ap_mmn.h. The module API version
560 corresponds to the version of Apache in use (in
561 the release version of Apache 1.3.14, for
562 instance, it is 19990320:10), but is mainly of
563 interest to module authors.</dd>
565 <dt><code>THE_REQUEST</code></dt>
567 <dd>The full HTTP request line sent by the
568 browser to the server (e.g., "<code>GET
569 /index.html HTTP/1.1</code>"). This does not
570 include any additional headers sent by the
573 <dt><code>REQUEST_URI</code></dt>
575 <dd>The resource requested in the HTTP request
576 line. (In the example above, this would be
579 <dt><code>REQUEST_FILENAME</code></dt>
581 <dd>The full local filesystem path to the file or
582 script matching the request.</dd>
588 <p>Special Notes:</p>
591 <li>The variables SCRIPT_FILENAME and REQUEST_FILENAME
592 contain the same value, <em>i.e.</em>, the value of the
593 <code>filename</code> field of the internal
594 <code>request_rec</code> structure of the Apache server.
595 The first name is just the commonly known CGI variable name
596 while the second is the consistent counterpart to
597 REQUEST_URI (which contains the value of the
598 <code>uri</code> field of <code>request_rec</code>).</li>
600 <li>There is the special format:
601 <code>%{ENV:variable}</code> where <em>variable</em> can be
602 any environment variable. This is looked-up via internal
603 Apache structures and (if not found there) via
604 <code>getenv()</code> from the Apache server process.</li>
606 <li>There is the special format:
607 <code>%{HTTP:header}</code> where <em>header</em> can be
608 any HTTP MIME-header name. This is looked-up from the HTTP
609 request. Example: <code>%{HTTP:Proxy-Connection}</code> is
610 the value of the HTTP header
611 ``<code>Proxy-Connection:</code>''.</li>
613 <li>There is the special format
614 <code>%{LA-U:variable}</code> for look-aheads which perform
615 an internal (URL-based) sub-request to determine the final
616 value of <em>variable</em>. Use this when you want to use a
617 variable for rewriting which is actually set later in an
618 API phase and thus is not available at the current stage.
619 For instance when you want to rewrite according to the
620 <code>REMOTE_USER</code> variable from within the
621 per-server context (<code>httpd.conf</code> file) you have
622 to use <code>%{LA-U:REMOTE_USER}</code> because this
623 variable is set by the authorization phases which come
624 <em>after</em> the URL translation phase where mod_rewrite
625 operates. On the other hand, because mod_rewrite implements
626 its per-directory context (<code>.htaccess</code> file) via
627 the Fixup phase of the API and because the authorization
628 phases come <em>before</em> this phase, you just can use
629 <code>%{REMOTE_USER}</code> there.</li>
631 <li>There is the special format:
632 <code>%{LA-F:variable}</code> which performs an internal
633 (filename-based) sub-request to determine the final value
634 of <em>variable</em>. Most of the time this is the same as
638 <p><em>CondPattern</em> is the condition pattern,
639 <em>i.e.</em>, a regular expression which is applied to the
640 current instance of the <em>TestString</em>, <em>i.e.</em>,
641 <em>TestString</em> is evaluated and then matched against
642 <em>CondPattern</em>.</p>
644 <p><strong>Remember:</strong> <em>CondPattern</em> is a
645 <em>perl compatible regular expression</em> with some
649 <li>You can prefix the pattern string with a
650 '<code>!</code>' character (exclamation mark) to specify a
651 <strong>non</strong>-matching pattern.</li>
654 There are some special variants of <em>CondPatterns</em>.
655 Instead of real regular expression strings you can also
656 use one of the following:
659 <li>'<strong><CondPattern</strong>' (is lexically
661 Treats the <em>CondPattern</em> as a plain string and
662 compares it lexically to <em>TestString</em>. True if
663 <em>TestString</em> is lexically lower than
664 <em>CondPattern</em>.</li>
666 <li>'<strong>>CondPattern</strong>' (is lexically
668 Treats the <em>CondPattern</em> as a plain string and
669 compares it lexically to <em>TestString</em>. True if
670 <em>TestString</em> is lexically greater than
671 <em>CondPattern</em>.</li>
673 <li>'<strong>=CondPattern</strong>' (is lexically
675 Treats the <em>CondPattern</em> as a plain string and
676 compares it lexically to <em>TestString</em>. True if
677 <em>TestString</em> is lexically equal to
678 <em>CondPattern</em>, i.e the two strings are exactly
679 equal (character by character). If <em>CondPattern</em>
680 is just <code>""</code> (two quotation marks) this
681 compares <em>TestString</em> to the empty string.</li>
683 <li>'<strong>-d</strong>' (is
684 <strong>d</strong>irectory)<br />
685 Treats the <em>TestString</em> as a pathname and tests
686 if it exists and is a directory.</li>
688 <li>'<strong>-f</strong>' (is regular
689 <strong>f</strong>ile)<br />
690 Treats the <em>TestString</em> as a pathname and tests
691 if it exists and is a regular file.</li>
693 <li>'<strong>-s</strong>' (is regular file with
694 <strong>s</strong>ize)<br />
695 Treats the <em>TestString</em> as a pathname and tests
696 if it exists and is a regular file with size greater
699 <li>'<strong>-l</strong>' (is symbolic
700 <strong>l</strong>ink)<br />
701 Treats the <em>TestString</em> as a pathname and tests
702 if it exists and is a symbolic link.</li>
704 <li>'<strong>-F</strong>' (is existing file via
706 Checks if <em>TestString</em> is a valid file and
707 accessible via all the server's currently-configured
708 access controls for that path. This uses an internal
709 subrequest to determine the check, so use it with care
710 because it decreases your servers performance!</li>
712 <li>'<strong>-U</strong>' (is existing URL via
714 Checks if <em>TestString</em> is a valid URL and
715 accessible via all the server's currently-configured
716 access controls for that path. This uses an internal
717 subrequest to determine the check, so use it with care
718 because it decreases your server's performance!</li>
721 <div class="note"><h3>Notice</h3>
722 All of these tests can
723 also be prefixed by an exclamation mark ('!') to
724 negate their meaning.
729 <p>Additionally you can set special flags for
730 <em>CondPattern</em> by appending</p>
733 <strong><code>[</code><em>flags</em><code>]</code></strong>
736 <p>as the third argument to the <code>RewriteCond</code>
737 directive. <em>Flags</em> is a comma-separated list of the
741 <li>'<strong><code>nocase|NC</code></strong>'
742 (<strong>n</strong>o <strong>c</strong>ase)<br />
743 This makes the test case-insensitive, <em>i.e.</em>, there
744 is no difference between 'A-Z' and 'a-z' both in the
745 expanded <em>TestString</em> and the <em>CondPattern</em>.
746 This flag is effective only for comparisons between
747 <em>TestString</em> and <em>CondPattern</em>. It has no
748 effect on filesystem and subrequest checks.</li>
751 '<strong><code>ornext|OR</code></strong>'
752 (<strong>or</strong> next condition)<br />
753 Use this to combine rule conditions with a local OR
754 instead of the implicit AND. Typical example:
756 <div class="example"><pre>
757 RewriteCond %{REMOTE_HOST} ^host1.* [OR]
758 RewriteCond %{REMOTE_HOST} ^host2.* [OR]
759 RewriteCond %{REMOTE_HOST} ^host3.*
760 RewriteRule ...some special stuff for any of these hosts...
763 Without this flag you would have to write the cond/rule
768 <p><strong>Example:</strong></p>
770 <p>To rewrite the Homepage of a site according to the
771 ``<code>User-Agent:</code>'' header of the request, you can
772 use the following: </p>
774 <div class="example"><pre>
775 RewriteCond %{HTTP_USER_AGENT} ^Mozilla.*
776 RewriteRule ^/$ /homepage.max.html [L]
778 RewriteCond %{HTTP_USER_AGENT} ^Lynx.*
779 RewriteRule ^/$ /homepage.min.html [L]
781 RewriteRule ^/$ /homepage.std.html [L]
784 <p>Interpretation: If you use Netscape Navigator as your
785 browser (which identifies itself as 'Mozilla'), then you
786 get the max homepage, which includes Frames, <em>etc.</em>
787 If you use the Lynx browser (which is Terminal-based), then
788 you get the min homepage, which contains no images, no
789 tables, <em>etc.</em> If you use any other browser you get
790 the standard homepage.</p>
794 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
795 <div class="directive-section"><h2><a name="RewriteEngine" id="RewriteEngine">RewriteEngine</a> <a name="rewriteengine" id="rewriteengine">Directive</a></h2>
796 <table class="directive">
797 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Enables or disables runtime rewriting engine</td></tr>
798 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>RewriteEngine on|off</code></td></tr>
799 <tr><th><a href="directive-dict.html#Default">Default:</a></th><td><code>RewriteEngine off</code></td></tr>
800 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
801 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>FileInfo</td></tr>
802 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Extension</td></tr>
803 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_rewrite</td></tr>
806 <p>The <code class="directive">RewriteEngine</code> directive enables or
807 disables the runtime rewriting engine. If it is set to
808 <code>off</code> this module does no runtime processing at
809 all. It does not even update the <code>SCRIPT_URx</code>
810 environment variables.</p>
812 <p>Use this directive to disable the module instead of
813 commenting out all the <code class="directive"><a href="#rewriterule">RewriteRule</a></code> directives!</p>
815 <p>Note that, by default, rewrite configurations are not
816 inherited. This means that you need to have a
817 <code>RewriteEngine on</code> directive for each virtual host
818 in which you wish to use it.</p>
821 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
822 <div class="directive-section"><h2><a name="RewriteLock" id="RewriteLock">RewriteLock</a> <a name="rewritelock" id="rewritelock">Directive</a></h2>
823 <table class="directive">
824 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Sets the name of the lock file used for RewriteMap
825 synchronization</td></tr>
826 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>RewriteLock <em>file-path</em></code></td></tr>
827 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config</td></tr>
828 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Extension</td></tr>
829 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_rewrite</td></tr>
831 <p>This directive sets the filename for a synchronization
832 lockfile which mod_rewrite needs to communicate with <code class="directive"><a href="#rewritemap">RewriteMap</a></code>
833 <em>programs</em>. Set this lockfile to a local path (not on a
834 NFS-mounted device) when you want to use a rewriting
835 map-program. It is not required for other types of rewriting
839 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
840 <div class="directive-section"><h2><a name="RewriteLog" id="RewriteLog">RewriteLog</a> <a name="rewritelog" id="rewritelog">Directive</a></h2>
841 <table class="directive">
842 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Sets the name of the file used for logging rewrite engine
844 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>RewriteLog <em>file-path</em></code></td></tr>
845 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host</td></tr>
846 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Extension</td></tr>
847 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_rewrite</td></tr>
849 <p>The <code class="directive">RewriteLog</code> directive sets the name
850 of the file to which the server logs any rewriting actions it
851 performs. If the name does not begin with a slash
852 ('<code>/</code>') then it is assumed to be relative to the
853 <em>Server Root</em>. The directive should occur only once per
856 <div class="note"> To disable the logging of
857 rewriting actions it is not recommended to set
858 <em>Filename</em> to <code>/dev/null</code>, because
859 although the rewriting engine does not then output to a
860 logfile it still creates the logfile output internally.
861 <strong>This will slow down the server with no advantage
862 to the administrator!</strong> To disable logging either
863 remove or comment out the <code class="directive">RewriteLog</code>
864 directive or use <code>RewriteLogLevel 0</code>!
867 <div class="note"><h3>Security</h3>
869 See the <a href="../misc/security_tips.html">Apache Security Tips</a>
870 document for details on why your security could be compromised if the
871 directory where logfiles are stored is writable by anyone other than
872 the user that starts the server.
875 <div class="example"><h3>Example</h3><p><code>
876 RewriteLog "/usr/local/var/apache/logs/rewrite.log"
881 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
882 <div class="directive-section"><h2><a name="RewriteLogLevel" id="RewriteLogLevel">RewriteLogLevel</a> <a name="rewriteloglevel" id="rewriteloglevel">Directive</a></h2>
883 <table class="directive">
884 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Sets the verbosity of the log file used by the rewrite
886 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>RewriteLogLevel <em>Level</em></code></td></tr>
887 <tr><th><a href="directive-dict.html#Default">Default:</a></th><td><code>RewriteLogLevel 0</code></td></tr>
888 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host</td></tr>
889 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Extension</td></tr>
890 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_rewrite</td></tr>
892 <p>The <code class="directive">RewriteLogLevel</code> directive sets the
893 verbosity level of the rewriting logfile. The default level 0
894 means no logging, while 9 or more means that practically all
895 actions are logged.</p>
897 <p>To disable the logging of rewriting actions simply set
898 <em>Level</em> to 0. This disables all rewrite action
901 <div class="note"> Using a high value for
902 <em>Level</em> will slow down your Apache server
903 dramatically! Use the rewriting logfile at a
904 <em>Level</em> greater than 2 only for debugging!
907 <div class="example"><h3>Example</h3><p><code>
913 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
914 <div class="directive-section"><h2><a name="RewriteMap" id="RewriteMap">RewriteMap</a> <a name="rewritemap" id="rewritemap">Directive</a></h2>
915 <table class="directive">
916 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Defines a mapping function for key-lookup</td></tr>
917 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>RewriteMap <em>MapName</em> <em>MapType</em>:<em>MapSource</em>
919 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host</td></tr>
920 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Extension</td></tr>
921 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_rewrite</td></tr>
922 <tr><th><a href="directive-dict.html#Compatibility">Compatibility:</a></th><td>The choice of different dbm types is available in
923 Apache 2.0.41 and later</td></tr>
925 <p>The <code class="directive">RewriteMap</code> directive defines a
926 <em>Rewriting Map</em> which can be used inside rule
927 substitution strings by the mapping-functions to
928 insert/substitute fields through a key lookup. The source of
929 this lookup can be of various types.</p>
931 <p>The <a id="mapfunc" name="mapfunc"><em>MapName</em></a> is
932 the name of the map and will be used to specify a
933 mapping-function for the substitution strings of a rewriting
934 rule via one of the following constructs:</p>
937 <strong><code>${</code> <em>MapName</em> <code>:</code>
938 <em>LookupKey</em> <code>}</code><br />
939 <code>${</code> <em>MapName</em> <code>:</code>
940 <em>LookupKey</em> <code>|</code> <em>DefaultValue</em>
941 <code>}</code></strong>
944 <p>When such a construct occurs the map <em>MapName</em> is
945 consulted and the key <em>LookupKey</em> is looked-up. If the
946 key is found, the map-function construct is substituted by
947 <em>SubstValue</em>. If the key is not found then it is
948 substituted by <em>DefaultValue</em> or by the empty string
949 if no <em>DefaultValue</em> was specified.</p>
951 <p>The following combinations for <em>MapType</em> and
952 <em>MapSource</em> can be used:</p>
956 <strong>Standard Plain Text</strong><br />
957 MapType: <code>txt</code>, MapSource: Unix filesystem
958 path to valid regular file
960 <p>This is the standard rewriting map feature where the
961 <em>MapSource</em> is a plain ASCII file containing
962 either blank lines, comment lines (starting with a '#'
963 character) or pairs like the following - one per
967 <strong><em>MatchingKey</em>
968 <em>SubstValue</em></strong>
971 <div class="example"><h3>Example</h3><pre>
973 ## map.txt -- rewriting map
976 Ralf.S.Engelschall rse # Bastard Operator From Hell
977 Mr.Joe.Average joe # Mr. Average
980 <div class="example"><p><code>
981 RewriteMap real-to-user txt:/path/to/file/map.txt
986 <strong>Randomized Plain Text</strong><br />
987 MapType: <code>rnd</code>, MapSource: Unix filesystem
988 path to valid regular file
990 <p>This is identical to the Standard Plain Text variant
991 above but with a special post-processing feature: After
992 looking up a value it is parsed according to contained
993 ``<code>|</code>'' characters which have the meaning of
994 ``or''. In other words they indicate a set of
995 alternatives from which the actual returned value is
996 chosen randomly. Although this sounds crazy and useless,
997 it was actually designed for load balancing in a reverse
998 proxy situation where the looked up values are server
1001 <div class="example"><pre>
1003 ## map.txt -- rewriting map
1006 static www1|www2|www3|www4
1010 <div class="example"><p><code>
1011 RewriteMap servers rnd:/path/to/file/map.txt
1016 <strong>Hash File</strong><br /> MapType:
1017 <code>dbm[=<em>type</em>]</code>, MapSource: Unix filesystem
1018 path to valid regular file
1020 <p>Here the source is a binary format DBM file containing
1021 the same contents as a <em>Plain Text</em> format file, but
1022 in a special representation which is optimized for really
1023 fast lookups. The <em>type</em> can be sdbm, gdbm, ndbm, or
1024 db depending on <a href="../install.html#dbm">compile-time
1025 settings</a>. If the <em>type</em> is ommitted, the
1026 compile-time default will be chosen. You can create such a
1027 file with any DBM tool or with the following Perl
1028 script. Be sure to adjust it to create the appropriate
1029 type of DBM. The example creates an NDBM file.</p>
1031 <div class="example"><pre>
1034 ## txt2dbm -- convert txt map to dbm format
1040 ($txtmap, $dbmmap) = @ARGV;
1042 open(TXT, "<$txtmap") or die "Couldn't open $txtmap!\n";
1043 tie (%DB, 'NDBM_File', $dbmmap,O_RDWR|O_TRUNC|O_CREAT, 0644)
1044 or die "Couldn't create $dbmmap!\n";
1046 while (<TXT>) {
1047 next if (/^\s*#/ or /^\s*$/);
1048 $DB{$1} = $2 if (/^\s*(\S+)\s+(\S+)/);
1055 <div class="example"><p><code>
1056 $ txt2dbm map.txt map.db
1061 <strong>Internal Function</strong><br />
1062 MapType: <code>int</code>, MapSource: Internal Apache
1065 <p>Here the source is an internal Apache function.
1066 Currently you cannot create your own, but the following
1067 functions already exists:</p>
1070 <li><strong>toupper</strong>:<br />
1071 Converts the looked up key to all upper case.</li>
1073 <li><strong>tolower</strong>:<br />
1074 Converts the looked up key to all lower case.</li>
1076 <li><strong>escape</strong>:<br />
1077 Translates special characters in the looked up key to
1080 <li><strong>unescape</strong>:<br />
1081 Translates hex-encodings in the looked up key back to
1082 special characters.</li>
1087 <strong>External Rewriting Program</strong><br />
1088 MapType: <code>prg</code>, MapSource: Unix filesystem
1089 path to valid regular file
1091 <p>Here the source is a program, not a map file. To
1092 create it you can use the language of your choice, but
1093 the result has to be a executable (<em>i.e.</em>, either
1094 object-code or a script with the magic cookie trick
1095 '<code>#!/path/to/interpreter</code>' as the first
1098 <p>This program is started once at startup of the Apache
1099 servers and then communicates with the rewriting engine
1100 over its <code>stdin</code> and <code>stdout</code>
1101 file-handles. For each map-function lookup it will
1102 receive the key to lookup as a newline-terminated string
1103 on <code>stdin</code>. It then has to give back the
1104 looked-up value as a newline-terminated string on
1105 <code>stdout</code> or the four-character string
1106 ``<code>NULL</code>'' if it fails (<em>i.e.</em>, there
1107 is no corresponding value for the given key). A trivial
1108 program which will implement a 1:1 map (<em>i.e.</em>,
1109 key == value) could be:</p>
1111 <div class="example"><pre>
1114 while (<STDIN>) {
1115 # ...put here any transformations or lookups...
1120 <p>But be very careful:</p>
1123 <li>``<em>Keep it simple, stupid</em>'' (KISS), because
1124 if this program hangs it will hang the Apache server
1125 when the rule occurs.</li>
1127 <li>Avoid one common mistake: never do buffered I/O on
1128 <code>stdout</code>! This will cause a deadloop! Hence
1129 the ``<code>$|=1</code>'' in the above example...</li>
1131 <li>Use the <code class="directive"><a href="#rewritelock">RewriteLock</a></code> directive to
1132 define a lockfile mod_rewrite can use to synchronize the
1133 communication to the program. By default no such
1134 synchronization takes place.</li>
1138 <p>The <code class="directive">RewriteMap</code> directive can occur more than
1139 once. For each mapping-function use one
1140 <code class="directive">RewriteMap</code> directive to declare its rewriting
1141 mapfile. While you cannot <strong>declare</strong> a map in
1142 per-directory context it is of course possible to
1143 <strong>use</strong> this map in per-directory context. </p>
1145 <div class="note"><h3>Note</h3> For plain text and DBM format files the
1146 looked-up keys are cached in-core until the <code>mtime</code> of the
1147 mapfile changes or the server does a restart. This way you can have
1148 map-functions in rules which are used for <strong>every</strong>
1149 request. This is no problem, because the external lookup only happens
1155 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1156 <div class="directive-section"><h2><a name="RewriteOptions" id="RewriteOptions">RewriteOptions</a> <a name="rewriteoptions" id="rewriteoptions">Directive</a></h2>
1157 <table class="directive">
1158 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Sets some special options for the rewrite engine</td></tr>
1159 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>RewriteOptions <var>Options</var></code></td></tr>
1160 <tr><th><a href="directive-dict.html#Default">Default:</a></th><td><code>RewriteOptions MaxRedirects=10</code></td></tr>
1161 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
1162 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>FileInfo</td></tr>
1163 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Extension</td></tr>
1164 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_rewrite</td></tr>
1165 <tr><th><a href="directive-dict.html#Compatibility">Compatibility:</a></th><td><code>MaxRedirects</code> is available in Apache 2.0.45 and
1169 <p>The <code class="directive">RewriteOptions</code> directive sets some
1170 special options for the current per-server or per-directory
1171 configuration. The <em>Option</em> strings can be one of the
1175 <dt><code>inherit</code></dt>
1176 <dd>This forces the current configuration to inherit the
1177 configuration of the parent. In per-virtual-server context
1178 this means that the maps, conditions and rules of the main
1179 server are inherited. In per-directory context this means
1180 that conditions and rules of the parent directory's
1181 <code>.htaccess</code> configuration are inherited.</dd>
1183 <dt><code>MaxRedirects=<var>number</var></code></dt>
1184 <dd>In order to prevent endless loops of internal redirects
1185 issued by per-directory <code class="directive"><a href="#rewriterule">RewriteRule</a></code>s, <code class="module"><a href="../mod/mod_rewrite.html">mod_rewrite</a></code> aborts
1186 the request after reaching a maximum number of such redirects and
1187 responds with an 500 Internal Server Error. If you really need
1188 more internal redirects than 10 per request, you may increase
1189 the default to the desired value.</dd>
1193 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1194 <div class="directive-section"><h2><a name="RewriteRule" id="RewriteRule">RewriteRule</a> <a name="rewriterule" id="rewriterule">Directive</a></h2>
1195 <table class="directive">
1196 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Defines rules for the rewriting engine</td></tr>
1197 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>RewriteRule
1198 <em>Pattern</em> <em>Substitution</em></code></td></tr>
1199 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
1200 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>FileInfo</td></tr>
1201 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Extension</td></tr>
1202 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_rewrite</td></tr>
1203 <tr><th><a href="directive-dict.html#Compatibility">Compatibility:</a></th><td>The cookie-flag is available in Apache 2.0.40 and later.</td></tr>
1205 <p>The <code class="directive">RewriteRule</code> directive is the real
1206 rewriting workhorse. The directive can occur more than once.
1207 Each directive then defines one single rewriting rule. The
1208 <strong>definition order</strong> of these rules is
1209 <strong>important</strong>, because this order is used when
1210 applying the rules at run-time.</p>
1212 <p><a id="patterns" name="patterns"><em>Pattern</em></a> is
1213 a perl compatible <a id="regexp" name="regexp">regular
1214 expression</a> which gets applied to the current URL. Here
1215 ``current'' means the value of the URL when this rule gets
1216 applied. This may not be the originally requested URL,
1217 because any number of rules may already have matched and made
1218 alterations to it.</p>
1220 <p>Some hints about the syntax of regular expressions:</p>
1222 <div class="note"><pre>
1223 <strong>Text:</strong>
1224 <strong><code>.</code></strong> Any single character
1225 <strong><code>[</code></strong>chars<strong><code>]</code></strong> Character class: One of chars
1226 <strong><code>[^</code></strong>chars<strong><code>]</code></strong> Character class: None of chars
1227 text1<strong><code>|</code></strong>text2 Alternative: text1 or text2
1229 <strong>Quantifiers:</strong>
1230 <strong><code>?</code></strong> 0 or 1 of the preceding text
1231 <strong><code>*</code></strong> 0 or N of the preceding text (N > 0)
1232 <strong><code>+</code></strong> 1 or N of the preceding text (N > 1)
1234 <strong>Grouping:</strong>
1235 <strong><code>(</code></strong>text<strong><code>)</code></strong> Grouping of text
1236 (either to set the borders of an alternative or
1237 for making backreferences where the <strong>N</strong>th group can
1238 be used on the RHS of a RewriteRule with <code>$</code><strong>N</strong>)
1240 <strong>Anchors:</strong>
1241 <strong><code>^</code></strong> Start of line anchor
1242 <strong><code>$</code></strong> End of line anchor
1244 <strong>Escaping:</strong>
1245 <strong><code>\</code></strong>char escape that particular char
1246 (for instance to specify the chars "<code>.[]()</code>" <em>etc.</em>)
1249 <p>For more information about regular expressions have a look at the
1250 perl regular expression manpage ("<a href="http://www.perldoc.com/perl5.6.1/pod/perlre.html">perldoc
1251 perlre</a>"). If you are interested in more detailed
1252 information about regular expressions and their variants
1253 (POSIX regex <em>etc.</em>) have a look at the
1254 following dedicated book on this topic:</p>
1257 <em>Mastering Regular Expressions</em><br />
1258 Jeffrey E.F. Friedl<br />
1259 Nutshell Handbook Series<br />
1260 O'Reilly & Associates, Inc. 1997<br />
1261 ISBN 1-56592-257-3<br />
1264 <p>Additionally in mod_rewrite the NOT character
1265 ('<code>!</code>') is a possible pattern prefix. This gives
1266 you the ability to negate a pattern; to say, for instance:
1267 ``<em>if the current URL does <strong>NOT</strong> match this
1268 pattern</em>''. This can be used for exceptional cases, where
1269 it is easier to match the negative pattern, or as a last
1272 <div class="note"><h3>Notice</h3>
1273 When using the NOT character
1274 to negate a pattern you cannot have grouped wildcard
1275 parts in the pattern. This is impossible because when the
1276 pattern does NOT match, there are no contents for the
1277 groups. In consequence, if negated patterns are used, you
1278 cannot use <code>$N</code> in the substitution
1282 <p><a id="rhs" name="rhs"><em>Substitution</em></a> of a
1283 rewriting rule is the string which is substituted for (or
1284 replaces) the original URL for which <em>Pattern</em>
1285 matched. Beside plain text you can use</p>
1288 <li>back-references <code>$N</code> to the RewriteRule
1291 <li>back-references <code>%N</code> to the last matched
1292 RewriteCond pattern</li>
1294 <li>server-variables as in rule condition test-strings
1295 (<code>%{VARNAME}</code>)</li>
1297 <li><a href="#mapfunc">mapping-function</a> calls
1298 (<code>${mapname:key|default}</code>)</li>
1300 <p>Back-references are <code>$</code><strong>N</strong>
1301 (<strong>N</strong>=0..9) identifiers which will be replaced
1302 by the contents of the <strong>N</strong>th group of the
1303 matched <em>Pattern</em>. The server-variables are the same
1304 as for the <em>TestString</em> of a <code>RewriteCond</code>
1305 directive. The mapping-functions come from the
1306 <code>RewriteMap</code> directive and are explained there.
1307 These three types of variables are expanded in the order of
1308 the above list. </p>
1310 <p>As already mentioned above, all the rewriting rules are
1311 applied to the <em>Substitution</em> (in the order of
1312 definition in the config file). The URL is <strong>completely
1313 replaced</strong> by the <em>Substitution</em> and the
1314 rewriting process goes on until there are no more rules
1315 unless explicitly terminated by a
1316 <code><strong>L</strong></code> flag - see below.</p>
1318 <p>There is a special substitution string named
1319 '<code>-</code>' which means: <strong>NO
1320 substitution</strong>! Sounds silly? No, it is useful to
1321 provide rewriting rules which <strong>only</strong> match
1322 some URLs but do no substitution, <em>e.g.</em>, in
1323 conjunction with the <strong>C</strong> (chain) flag to be
1324 able to have more than one pattern to be applied before a
1325 substitution occurs.</p>
1327 <p>One more note: You can even create URLs in the
1328 substitution string containing a query string part. Just use
1329 a question mark inside the substitution string to indicate
1330 that the following stuff should be re-injected into the
1331 QUERY_STRING. When you want to erase an existing query
1332 string, end the substitution string with just the question
1335 <div class="note"><h3>Note</h3>
1336 There is a special feature:
1337 When you prefix a substitution field with
1338 <code>http://</code><em>thishost</em>[<em>:thisport</em>]
1339 then <strong>mod_rewrite</strong> automatically strips it
1340 out. This auto-reduction on implicit external redirect
1341 URLs is a useful and important feature when used in
1342 combination with a mapping-function which generates the
1343 hostname part. Have a look at the first example in the
1344 example section below to understand this.
1347 <div class="note"><h3>Remember</h3>
1348 An unconditional external
1349 redirect to your own server will not work with the prefix
1350 <code>http://thishost</code> because of this feature. To
1351 achieve such a self-redirect, you have to use the
1352 <strong>R</strong>-flag (see below).
1355 <p>Additionally you can set special flags for
1356 <em>Substitution</em> by appending</p>
1359 <strong><code>[</code><em>flags</em><code>]</code></strong>
1362 as the third argument to the <code>RewriteRule</code>
1363 directive. <em>Flags</em> is a comma-separated list of the
1364 following flags: </p>
1368 '<strong><code>redirect|R</code>
1369 [=<em>code</em>]</strong>' (force <a id="redirect" name="redirect"><strong>r</strong>edirect</a>)<br />
1370 Prefix <em>Substitution</em> with
1371 <code>http://thishost[:thisport]/</code> (which makes the
1372 new URL a URI) to force a external redirection. If no
1373 <em>code</em> is given a HTTP response of 302 (MOVED
1374 TEMPORARILY) is used. If you want to use other response
1375 codes in the range 300-400 just specify them as a number
1376 or use one of the following symbolic names:
1377 <code>temp</code> (default), <code>permanent</code>,
1378 <code>seeother</code>. Use it for rules which should
1379 canonicalize the URL and give it back to the client,
1380 <em>e.g.</em>, translate ``<code>/~</code>'' into
1381 ``<code>/u/</code>'' or always append a slash to
1382 <code>/u/</code><em>user</em>, etc.<br />
1385 <p><strong>Note:</strong> When you use this flag, make
1386 sure that the substitution field is a valid URL! If not,
1387 you are redirecting to an invalid location! And remember
1388 that this flag itself only prefixes the URL with
1389 <code>http://thishost[:thisport]/</code>, rewriting
1390 continues. Usually you also want to stop and do the
1391 redirection immediately. To stop the rewriting you also
1392 have to provide the 'L' flag.</p>
1395 <li>'<strong><code>forbidden|F</code></strong>' (force URL
1396 to be <strong>f</strong>orbidden)<br />
1397 This forces the current URL to be forbidden,
1398 <em>i.e.</em>, it immediately sends back a HTTP response of
1399 403 (FORBIDDEN). Use this flag in conjunction with
1400 appropriate RewriteConds to conditionally block some
1403 <li>'<strong><code>gone|G</code></strong>' (force URL to be
1404 <strong>g</strong>one)<br />
1405 This forces the current URL to be gone, <em>i.e.</em>, it
1406 immediately sends back a HTTP response of 410 (GONE). Use
1407 this flag to mark pages which no longer exist as gone.</li>
1410 '<strong><code>proxy|P</code></strong>' (force
1411 <strong>p</strong>roxy)<br />
1412 This flag forces the substitution part to be internally
1413 forced as a proxy request and immediately (<em>i.e.</em>,
1414 rewriting rule processing stops here) put through the <a href="mod_proxy.html">proxy module</a>. You have to make
1415 sure that the substitution string is a valid URI
1416 (<em>e.g.</em>, typically starting with
1417 <code>http://</code><em>hostname</em>) which can be
1418 handled by the Apache proxy module. If not you get an
1419 error from the proxy module. Use this flag to achieve a
1420 more powerful implementation of the <a href="mod_proxy.html#proxypass">ProxyPass</a> directive,
1421 to map some remote stuff into the namespace of the local
1424 <p>Notice: To use this functionality make sure you have
1425 the proxy module compiled into your Apache server
1426 program. If you don't know please check whether
1427 <code>mod_proxy.c</code> is part of the ``<code>httpd
1428 -l</code>'' output. If yes, this functionality is
1429 available to mod_rewrite. If not, then you first have to
1430 rebuild the ``<code>httpd</code>'' program with mod_proxy
1434 <li>'<strong><code>last|L</code></strong>'
1435 (<strong>l</strong>ast rule)<br />
1436 Stop the rewriting process here and don't apply any more
1437 rewriting rules. This corresponds to the Perl
1438 <code>last</code> command or the <code>break</code> command
1439 from the C language. Use this flag to prevent the currently
1440 rewritten URL from being rewritten further by following
1441 rules. For example, use it to rewrite the root-path URL
1442 ('<code>/</code>') to a real one, <em>e.g.</em>,
1443 '<code>/e/www/</code>'.</li>
1445 <li>'<strong><code>next|N</code></strong>'
1446 (<strong>n</strong>ext round)<br />
1447 Re-run the rewriting process (starting again with the
1448 first rewriting rule). Here the URL to match is again not
1449 the original URL but the URL from the last rewriting rule.
1450 This corresponds to the Perl <code>next</code> command or
1451 the <code>continue</code> command from the C language. Use
1452 this flag to restart the rewriting process, <em>i.e.</em>,
1453 to immediately go to the top of the loop.<br />
1454 <strong>But be careful not to create an infinite
1457 <li>'<strong><code>chain|C</code></strong>'
1458 (<strong>c</strong>hained with next rule)<br />
1459 This flag chains the current rule with the next rule
1460 (which itself can be chained with the following rule,
1461 <em>etc.</em>). This has the following effect: if a rule
1462 matches, then processing continues as usual, <em>i.e.</em>,
1463 the flag has no effect. If the rule does
1464 <strong>not</strong> match, then all following chained
1465 rules are skipped. For instance, use it to remove the
1466 ``<code>.www</code>'' part inside a per-directory rule set
1467 when you let an external redirect happen (where the
1468 ``<code>.www</code>'' part should not to occur!).</li>
1471 '<strong><code>type|T</code></strong>=<em>MIME-type</em>'
1472 (force MIME <strong>t</strong>ype)<br />
1473 Force the MIME-type of the target file to be
1474 <em>MIME-type</em>. For instance, this can be used to
1475 simulate the <code>mod_alias</code> directive
1476 <code>ScriptAlias</code> which internally forces all files
1477 inside the mapped directory to have a MIME type of
1478 ``<code>application/x-httpd-cgi</code>''.</li>
1481 '<strong><code>nosubreq|NS</code></strong>' (used only if
1482 <strong>n</strong>o internal
1483 <strong>s</strong>ub-request)<br />
1484 This flag forces the rewriting engine to skip a
1485 rewriting rule if the current request is an internal
1486 sub-request. For instance, sub-requests occur internally
1487 in Apache when <code>mod_include</code> tries to find out
1488 information about possible directory default files
1489 (<code>index.xxx</code>). On sub-requests it is not
1490 always useful and even sometimes causes a failure to if
1491 the complete set of rules are applied. Use this flag to
1492 exclude some rules.<br />
1495 <p>Use the following rule for your decision: whenever you
1496 prefix some URLs with CGI-scripts to force them to be
1497 processed by the CGI-script, the chance is high that you
1498 will run into problems (or even overhead) on
1499 sub-requests. In these cases, use this flag.</p>
1502 <li>'<strong><code>nocase|NC</code></strong>'
1503 (<strong>n</strong>o <strong>c</strong>ase)<br />
1504 This makes the <em>Pattern</em> case-insensitive,
1505 <em>i.e.</em>, there is no difference between 'A-Z' and
1506 'a-z' when <em>Pattern</em> is matched against the current
1509 <li>'<strong><code>qsappend|QSA</code></strong>'
1510 (<strong>q</strong>uery <strong>s</strong>tring
1511 <strong>a</strong>ppend)<br />
1512 This flag forces the rewriting engine to append a query
1513 string part in the substitution string to the existing one
1514 instead of replacing it. Use this when you want to add more
1515 data to the query string via a rewrite rule.</li>
1518 '<strong><code>noescape|NE</code></strong>'
1519 (<strong>n</strong>o URI <strong>e</strong>scaping of
1521 This flag keeps mod_rewrite from applying the usual URI
1522 escaping rules to the result of a rewrite. Ordinarily,
1523 special characters (such as '%', '$', ';', and so on)
1524 will be escaped into their hexcode equivalents ('%25',
1525 '%24', and '%3B', respectively); this flag prevents this
1526 from being done. This allows percent symbols to appear in
1528 <div class="example"><p><code>
1529 RewriteRule /foo/(.*) /bar?arg=P1\%3d$1 [R,NE]
1532 which would turn '<code>/foo/zed</code>' into a safe
1533 request for '<code>/bar?arg=P1=zed</code>'.
1537 '<strong><code>passthrough|PT</code></strong>'
1538 (<strong>p</strong>ass <strong>t</strong>hrough to next
1540 This flag forces the rewriting engine to set the
1541 <code>uri</code> field of the internal
1542 <code>request_rec</code> structure to the value of the
1543 <code>filename</code> field. This flag is just a hack to
1544 be able to post-process the output of
1545 <code>RewriteRule</code> directives by
1546 <code>Alias</code>, <code>ScriptAlias</code>,
1547 <code>Redirect</code>, <em>etc.</em> directives from
1548 other URI-to-filename translators. A trivial example to
1549 show the semantics: If you want to rewrite
1550 <code>/abc</code> to <code>/def</code> via the rewriting
1551 engine of <code>mod_rewrite</code> and then
1552 <code>/def</code> to <code>/ghi</code> with
1553 <code>mod_alias</code>:
1554 <div class="example"><p><code>
1555 RewriteRule ^/abc(.*) /def$1 [PT]<br />
1558 If you omit the <code>PT</code> flag then
1559 <code>mod_rewrite</code> will do its job fine,
1560 <em>i.e.</em>, it rewrites <code>uri=/abc/...</code> to
1561 <code>filename=/def/...</code> as a full API-compliant
1562 URI-to-filename translator should do. Then
1563 <code>mod_alias</code> comes and tries to do a
1564 URI-to-filename transition which will not work.
1566 <p>Note: <strong>You have to use this flag if you want to
1567 intermix directives of different modules which contain
1568 URL-to-filename translators</strong>. The typical example
1569 is the use of <code>mod_alias</code> and
1570 <code>mod_rewrite</code>..</p>
1572 <div class="note"><h3>For Apache hackers</h3>
1573 If the current Apache API had a filename-to-filename
1574 hook additionally to the URI-to-filename hook then we
1575 wouldn't need this flag! But without such a hook this
1576 flag is the only solution. The Apache Group has
1577 discussed this problem and will add such a hook in
1582 <li>'<strong><code>skip|S</code></strong>=<em>num</em>'
1583 (<strong>s</strong>kip next rule(s))<br />
1584 This flag forces the rewriting engine to skip the next
1585 <em>num</em> rules in sequence when the current rule
1586 matches. Use this to make pseudo if-then-else constructs:
1587 The last rule of the then-clause becomes
1588 <code>skip=N</code> where N is the number of rules in the
1589 else-clause. (This is <strong>not</strong> the same as the
1590 'chain|C' flag!)</li>
1593 '<strong><code>env|E=</code></strong><em>VAR</em>:<em>VAL</em>'
1594 (set <strong>e</strong>nvironment variable)<br />
1595 This forces an environment variable named <em>VAR</em> to
1596 be set to the value <em>VAL</em>, where <em>VAL</em> can
1597 contain regexp backreferences <code>$N</code> and
1598 <code>%N</code> which will be expanded. You can use this
1599 flag more than once to set more than one variable. The
1600 variables can be later dereferenced in many situations, but
1601 usually from within XSSI (via <code><!--#echo
1602 var="VAR"--></code>) or CGI (<em>e.g.</em>
1603 <code>$ENV{'VAR'}</code>). Additionally you can dereference
1604 it in a following RewriteCond pattern via
1605 <code>%{ENV:VAR}</code>. Use this to strip but remember
1606 information from URLs.</li>
1609 '<strong><code>cookie|CO=</code></strong><em>NAME</em>:<em>VAL</em>:<em>domain</em>[:<em>lifetime</em>[:<em>path</em>]]'
1610 (set <strong>co</strong>cookie)<br />
1611 This sets a cookie on the client's browser. The cookie's name
1612 is specified by <em>NAME</em> and the value is
1613 <em>VAL</em>. The <em>domain</em> field is the domain of the
1614 cookie, such as '.apache.org',the optional <em>lifetime</em>
1615 is the lifetime of the cookie in minutes, and the optional
1616 <em>path</em> is the path of the cookie</li>
1620 <div class="note"><h3>Note</h3> Never forget that <em>Pattern</em> is
1621 applied to a complete URL in per-server configuration
1622 files. <strong>But in per-directory configuration files, the
1623 per-directory prefix (which always is the same for a specific
1624 directory!) is automatically <em>removed</em> for the pattern matching
1625 and automatically <em>added</em> after the substitution has been
1626 done.</strong> This feature is essential for many sorts of rewriting,
1627 because without this prefix stripping you have to match the parent
1628 directory which is not always possible.
1630 <p>There is one exception: If a substitution string
1631 starts with ``<code>http://</code>'' then the directory
1632 prefix will <strong>not</strong> be added and an
1633 external redirect or proxy throughput (if flag
1634 <strong>P</strong> is used!) is forced!</p>
1637 <div class="note"><h3>Note</h3>
1638 To enable the rewriting engine
1639 for per-directory configuration files you need to set
1640 ``<code>RewriteEngine On</code>'' in these files
1641 <strong>and</strong> ``<code>Options
1642 FollowSymLinks</code>'' must be enabled. If your
1643 administrator has disabled override of
1644 <code>FollowSymLinks</code> for a user's directory, then
1645 you cannot use the rewriting engine. This restriction is
1646 needed for security reasons.
1649 <p>Here are all possible substitution combinations and their
1652 <p><strong>Inside per-server configuration
1653 (<code>httpd.conf</code>)<br />
1654 for request ``<code>GET
1655 /somepath/pathinfo</code>'':</strong><br />
1658 <div class="note"><pre>
1659 <strong>Given Rule</strong> <strong>Resulting Substitution</strong>
1660 ---------------------------------------------- ----------------------------------
1661 ^/somepath(.*) otherpath$1 not supported, because invalid!
1663 ^/somepath(.*) otherpath$1 [R] not supported, because invalid!
1665 ^/somepath(.*) otherpath$1 [P] not supported, because invalid!
1666 ---------------------------------------------- ----------------------------------
1667 ^/somepath(.*) /otherpath$1 /otherpath/pathinfo
1669 ^/somepath(.*) /otherpath$1 [R] http://thishost/otherpath/pathinfo
1670 via external redirection
1672 ^/somepath(.*) /otherpath$1 [P] not supported, because silly!
1673 ---------------------------------------------- ----------------------------------
1674 ^/somepath(.*) http://thishost/otherpath$1 /otherpath/pathinfo
1676 ^/somepath(.*) http://thishost/otherpath$1 [R] http://thishost/otherpath/pathinfo
1677 via external redirection
1679 ^/somepath(.*) http://thishost/otherpath$1 [P] not supported, because silly!
1680 ---------------------------------------------- ----------------------------------
1681 ^/somepath(.*) http://otherhost/otherpath$1 http://otherhost/otherpath/pathinfo
1682 via external redirection
1684 ^/somepath(.*) http://otherhost/otherpath$1 [R] http://otherhost/otherpath/pathinfo
1685 via external redirection
1686 (the [R] flag is redundant)
1688 ^/somepath(.*) http://otherhost/otherpath$1 [P] http://otherhost/otherpath/pathinfo
1692 <p><strong>Inside per-directory configuration for
1693 <code>/somepath</code><br />
1694 (<em>i.e.</em>, file <code>.htaccess</code> in dir
1695 <code>/physical/path/to/somepath</code> containing
1696 <code>RewriteBase /somepath</code>)<br />
1697 for request ``<code>GET
1698 /somepath/localpath/pathinfo</code>'':</strong><br />
1701 <div class="note"><pre>
1702 <strong>Given Rule</strong> <strong>Resulting Substitution</strong>
1703 ---------------------------------------------- ----------------------------------
1704 ^localpath(.*) otherpath$1 /somepath/otherpath/pathinfo
1706 ^localpath(.*) otherpath$1 [R] http://thishost/somepath/otherpath/pathinfo
1707 via external redirection
1709 ^localpath(.*) otherpath$1 [P] not supported, because silly!
1710 ---------------------------------------------- ----------------------------------
1711 ^localpath(.*) /otherpath$1 /otherpath/pathinfo
1713 ^localpath(.*) /otherpath$1 [R] http://thishost/otherpath/pathinfo
1714 via external redirection
1716 ^localpath(.*) /otherpath$1 [P] not supported, because silly!
1717 ---------------------------------------------- ----------------------------------
1718 ^localpath(.*) http://thishost/otherpath$1 /otherpath/pathinfo
1720 ^localpath(.*) http://thishost/otherpath$1 [R] http://thishost/otherpath/pathinfo
1721 via external redirection
1723 ^localpath(.*) http://thishost/otherpath$1 [P] not supported, because silly!
1724 ---------------------------------------------- ----------------------------------
1725 ^localpath(.*) http://otherhost/otherpath$1 http://otherhost/otherpath/pathinfo
1726 via external redirection
1728 ^localpath(.*) http://otherhost/otherpath$1 [R] http://otherhost/otherpath/pathinfo
1729 via external redirection
1730 (the [R] flag is redundant)
1732 ^localpath(.*) http://otherhost/otherpath$1 [P] http://otherhost/otherpath/pathinfo
1736 <p><strong>Example:</strong></p>
1738 <p>We want to rewrite URLs of the form </p>
1741 <code>/</code> <em>Language</em> <code>/~</code>
1742 <em>Realname</em> <code>/.../</code> <em>File</em>
1748 <code>/u/</code> <em>Username</em> <code>/.../</code>
1749 <em>File</em> <code>.</code> <em>Language</em>
1752 <p>We take the rewrite mapfile from above and save it under
1753 <code>/path/to/file/map.txt</code>. Then we only have to
1754 add the following lines to the Apache server configuration
1757 <div class="example"><pre>
1758 RewriteLog /path/to/file/rewrite.log
1759 RewriteMap real-to-user txt:/path/to/file/map.txt
1760 RewriteRule ^/([^/]+)/~([^/]+)/(.*)$ /u/${real-to-user:$2|nobody}/$3.$1
1765 <div class="bottomlang">
1766 <p><span>Available Languages: </span><a href="../en/mod/mod_rewrite.html" title="English"> en </a></p>
1767 </div><div id="footer">
1768 <p class="apache">Maintained by the <a href="http://httpd.apache.org/docs-project/">Apache HTTP Server Documentation Project</a></p>
1769 <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>