2 <!DOCTYPE modulesynopsis SYSTEM "../style/modulesynopsis.dtd">
3 <?xml-stylesheet type="text/xsl" href="../style/manual.en.xsl"?>
6 Copyright 2002-2004 The Apache Software Foundation
8 Licensed under the Apache License, Version 2.0 (the "License");
9 you may not use this file except in compliance with the License.
10 You may obtain a copy of the License at
12 http://www.apache.org/licenses/LICENSE-2.0
14 Unless required by applicable law or agreed to in writing, software
15 distributed under the License is distributed on an "AS IS" BASIS,
16 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 See the License for the specific language governing permissions and
18 limitations under the License.
21 <modulesynopsis metafile="mod_rewrite.xml.meta">
23 <name>mod_rewrite</name>
25 <description>Provides a rule-based rewriting engine to rewrite requested
26 URLs on the fly</description>
28 <status>Extension</status>
29 <sourcefile>mod_rewrite.c</sourcefile>
30 <identifier>rewrite_module</identifier>
31 <compatibility>Available in Apache 1.3 and later</compatibility>
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 />
90 href="mailto:rse@engelschall.com"><code>rse@engelschall.com</code></a><br />
92 href="http://www.engelschall.com/"><code>www.engelschall.com</code></a>
96 <section id="Internal"><title>Internal Processing</title>
98 <p>The internal processing of this module is very complex but
99 needs to be explained once even to the average user to avoid
100 common mistakes and to let you exploit its full
103 <section id="InternalAPI"><title>API Phases</title>
105 <p>First you have to understand that when Apache processes a
106 HTTP request it does this in phases. A hook for each of these
107 phases is provided by the Apache API. Mod_rewrite uses two of
108 these hooks: the URL-to-filename translation hook which is
109 used after the HTTP request has been read but before any
110 authorization starts and the Fixup hook which is triggered
111 after the authorization phases and after the per-directory
112 config files (<code>.htaccess</code>) have been read, but
113 before the content handler is activated.</p>
115 <p>So, after a request comes in and Apache has determined the
116 corresponding server (or virtual server) the rewriting engine
117 starts processing of all mod_rewrite directives from the
118 per-server configuration in the URL-to-filename phase. A few
119 steps later when the final data directories are found, the
120 per-directory configuration directives of mod_rewrite are
121 triggered in the Fixup phase. In both situations mod_rewrite
122 rewrites URLs either to new URLs or to filenames, although
123 there is no obvious distinction between them. This is a usage
124 of the API which was not intended to be this way when the API
125 was designed, but as of Apache 1.x this is the only way
126 mod_rewrite can operate. To make this point more clear
127 remember the following two points:</p>
130 <li>Although mod_rewrite rewrites URLs to URLs, URLs to
131 filenames and even filenames to filenames, the API
132 currently provides only a URL-to-filename hook. In Apache
133 2.0 the two missing hooks will be added to make the
134 processing more clear. But this point has no drawbacks for
135 the user, it is just a fact which should be remembered:
136 Apache does more in the URL-to-filename hook than the API
140 Unbelievably mod_rewrite provides URL manipulations in
141 per-directory context, <em>i.e.</em>, within
142 <code>.htaccess</code> files, although these are reached
143 a very long time after the URLs have been translated to
144 filenames. It has to be this way because
145 <code>.htaccess</code> files live in the filesystem, so
146 processing has already reached this stage. In other
147 words: According to the API phases at this time it is too
148 late for any URL manipulations. To overcome this chicken
149 and egg problem mod_rewrite uses a trick: When you
150 manipulate a URL/filename in per-directory context
151 mod_rewrite first rewrites the filename back to its
152 corresponding URL (which is usually impossible, but see
153 the <code>RewriteBase</code> directive below for the
154 trick to achieve this) and then initiates a new internal
155 sub-request with the new URL. This restarts processing of
158 <p>Again mod_rewrite tries hard to make this complicated
159 step totally transparent to the user, but you should
160 remember here: While URL manipulations in per-server
161 context are really fast and efficient, per-directory
162 rewrites are slow and inefficient due to this chicken and
163 egg problem. But on the other hand this is the only way
164 mod_rewrite can provide (locally restricted) URL
165 manipulations to the average user.</p>
169 <p>Don't forget these two points!</p>
172 <section id="InternalRuleset"><title>Ruleset Processing</title>
174 <p>Now when mod_rewrite is triggered in these two API phases, it
175 reads the configured rulesets from its configuration
176 structure (which itself was either created on startup for
177 per-server context or during the directory walk of the Apache
178 kernel for per-directory context). Then the URL rewriting
179 engine is started with the contained ruleset (one or more
180 rules together with their conditions). The operation of the
181 URL rewriting engine itself is exactly the same for both
182 configuration contexts. Only the final result processing is
185 <p>The order of rules in the ruleset is important because the
186 rewriting engine processes them in a special (and not very
187 obvious) order. The rule is this: The rewriting engine loops
188 through the ruleset rule by rule (<directive
189 module="mod_rewrite">RewriteRule</directive> directives) and
190 when a particular rule matches it optionally loops through
191 existing corresponding conditions (<code>RewriteCond</code>
192 directives). For historical reasons the conditions are given
193 first, and so the control flow is a little bit long-winded. See
194 Figure 1 for more details.</p>
196 <img src="../images/mod_rewrite_fig1.gif" width="428"
197 height="385" alt="[Needs graphics capability to display]" /><br />
198 <dfn>Figure 1:</dfn>The control flow through the rewriting ruleset
200 <p>As you can see, first the URL is matched against the
201 <em>Pattern</em> of each rule. When it fails mod_rewrite
202 immediately stops processing this rule and continues with the
203 next rule. If the <em>Pattern</em> matches, mod_rewrite looks
204 for corresponding rule conditions. If none are present, it
205 just substitutes the URL with a new value which is
206 constructed from the string <em>Substitution</em> and goes on
207 with its rule-looping. But if conditions exist, it starts an
208 inner loop for processing them in the order that they are
209 listed. For conditions the logic is different: we don't match
210 a pattern against the current URL. Instead we first create a
211 string <em>TestString</em> by expanding variables,
212 back-references, map lookups, <em>etc.</em> and then we try
213 to match <em>CondPattern</em> against it. If the pattern
214 doesn't match, the complete set of conditions and the
215 corresponding rule fails. If the pattern matches, then the
216 next condition is processed until no more conditions are
217 available. If all conditions match, processing is continued
218 with the substitution of the URL with
219 <em>Substitution</em>.</p>
223 <section id="quoting"><title>Quoting Special Characters</title>
225 <p>As of Apache 1.3.20, special characters in
226 <em>TestString</em> and <em>Substitution</em> strings can be
227 escaped (that is, treated as normal characters without their
228 usual special meaning) by prefixing them with a slosh ('\')
229 character. In other words, you can include an actual
230 dollar-sign character in a <em>Substitution</em> string by
231 using '<code>\$</code>'; this keeps mod_rewrite from trying
232 to treat it as a backreference.</p>
235 <section id="InternalBackRefs"><title>Regex Back-Reference Availability</title>
237 <p>One important thing here has to be remembered: Whenever you
238 use parentheses in <em>Pattern</em> or in one of the
239 <em>CondPattern</em>, back-references are internally created
240 which can be used with the strings <code>$N</code> and
241 <code>%N</code> (see below). These are available for creating
242 the strings <em>Substitution</em> and <em>TestString</em>.
243 Figure 2 shows to which locations the back-references are
244 transfered for expansion.</p>
247 <img src="../images/mod_rewrite_fig2.gif" width="381"
248 height="179" alt="[Needs graphics capability to display]" /><br />
249 <dfn>Figure 2:</dfn> The back-reference flow through a rule.
251 <p>We know this was a crash course on mod_rewrite's internal
252 processing. But you will benefit from this knowledge when
253 reading the following documentation of the available
259 <section id="EnvVar"><title>Environment Variables</title>
261 <p>This module keeps track of two additional (non-standard)
262 CGI/SSI environment variables named <code>SCRIPT_URL</code>
263 and <code>SCRIPT_URI</code>. These contain the
264 <em>logical</em> Web-view to the current resource, while the
265 standard CGI/SSI variables <code>SCRIPT_NAME</code> and
266 <code>SCRIPT_FILENAME</code> contain the <em>physical</em>
269 <p>Notice: These variables hold the URI/URL <em>as they were
270 initially requested</em>, <em>i.e.</em>, <em>before</em> any
271 rewriting. This is important because the rewriting process is
272 primarily used to rewrite logical URLs to physical
275 <example><title>Example</title>
277 SCRIPT_NAME=/sw/lib/w3s/tree/global/u/rse/.www/index.html
278 SCRIPT_FILENAME=/u/rse/.www/index.html
280 SCRIPT_URI=http://en1.engelschall.com/u/rse/
286 <section id="Solutions"><title>Practical Solutions</title>
288 <p>We also have an <a href="../misc/rewriteguide.html">URL
289 Rewriting Guide</a> available, which provides a collection of
290 practical solutions for URL-based problems. There you can
291 find real-life rulesets and additional information about
297 <name>RewriteEngine</name>
298 <description>Enables or disables runtime rewriting engine</description>
299 <syntax>RewriteEngine on|off</syntax>
300 <default>RewriteEngine off</default>
301 <contextlist><context>server config</context><context>virtual host</context>
302 <context>directory</context><context>.htaccess</context></contextlist>
303 <override>FileInfo</override>
307 <p>The <directive>RewriteEngine</directive> directive enables or
308 disables the runtime rewriting engine. If it is set to
309 <code>off</code> this module does no runtime processing at
310 all. It does not even update the <code>SCRIPT_URx</code>
311 environment variables.</p>
313 <p>Use this directive to disable the module instead of
314 commenting out all the <directive
315 module="mod_rewrite">RewriteRule</directive> directives!</p>
317 <p>Note that, by default, rewrite configurations are not
318 inherited. This means that you need to have a
319 <code>RewriteEngine on</code> directive for each virtual host
320 in which you wish to use it.</p>
326 <name>RewriteOptions</name>
327 <description>Sets some special options for the rewrite engine</description>
328 <syntax>RewriteOptions <var>Options</var></syntax>
329 <default>RewriteOptions MaxRedirects=10</default>
330 <contextlist><context>server config</context><context>virtual host</context>
331 <context>directory</context><context>.htaccess</context></contextlist>
332 <override>FileInfo</override>
333 <compatibility><code>MaxRedirects</code> is available in Apache 2.0.45 and
334 later</compatibility>
337 <p>The <directive>RewriteOptions</directive> directive sets some
338 special options for the current per-server or per-directory
339 configuration. The <em>Option</em> strings can be one of the
343 <dt><code>inherit</code></dt>
344 <dd>This forces the current configuration to inherit the
345 configuration of the parent. In per-virtual-server context
346 this means that the maps, conditions and rules of the main
347 server are inherited. In per-directory context this means
348 that conditions and rules of the parent directory's
349 <code>.htaccess</code> configuration are inherited.</dd>
351 <dt><code>MaxRedirects=<var>number</var></code></dt>
352 <dd>In order to prevent endless loops of internal redirects
353 issued by per-directory <directive module="mod_rewrite"
354 >RewriteRule</directive>s, <module>mod_rewrite</module> aborts
355 the request after reaching a maximum number of such redirects and
356 responds with an 500 Internal Server Error. If you really need
357 more internal redirects than 10 per request, you may increase
358 the default to the desired value.</dd>
365 <name>RewriteLog</name>
366 <description>Sets the name of the file used for logging rewrite engine
367 processing</description>
368 <syntax>RewriteLog <em>file-path</em></syntax>
369 <contextlist><context>server config</context><context>virtual host</context>
373 <p>The <directive>RewriteLog</directive> directive sets the name
374 of the file to which the server logs any rewriting actions it
375 performs. If the name does not begin with a slash
376 ('<code>/</code>') then it is assumed to be relative to the
377 <em>Server Root</em>. The directive should occur only once per
380 <note> To disable the logging of
381 rewriting actions it is not recommended to set
382 <em>Filename</em> to <code>/dev/null</code>, because
383 although the rewriting engine does not then output to a
384 logfile it still creates the logfile output internally.
385 <strong>This will slow down the server with no advantage
386 to the administrator!</strong> To disable logging either
387 remove or comment out the <directive>RewriteLog</directive>
388 directive or use <code>RewriteLogLevel 0</code>!
391 <note type="securitywarning"><title>Security</title>
393 See the <a href="../misc/security_tips.html">Apache Security Tips</a>
394 document for details on why your security could be compromised if the
395 directory where logfiles are stored is writable by anyone other than
396 the user that starts the server.
399 <example><title>Example</title>
400 RewriteLog "/usr/local/var/apache/logs/rewrite.log"
408 <name>RewriteLogLevel</name>
409 <description>Sets the verbosity of the log file used by the rewrite
411 <syntax>RewriteLogLevel <em>Level</em></syntax>
412 <default>RewriteLogLevel 0</default>
413 <contextlist><context>server config</context><context>virtual host</context>
417 <p>The <directive>RewriteLogLevel</directive> directive sets the
418 verbosity level of the rewriting logfile. The default level 0
419 means no logging, while 9 or more means that practically all
420 actions are logged.</p>
422 <p>To disable the logging of rewriting actions simply set
423 <em>Level</em> to 0. This disables all rewrite action
426 <note> Using a high value for
427 <em>Level</em> will slow down your Apache server
428 dramatically! Use the rewriting logfile at a
429 <em>Level</em> greater than 2 only for debugging!
432 <example><title>Example</title>
441 <name>RewriteLock</name>
442 <description>Sets the name of the lock file used for <directive
443 module="mod_rewrite">RewriteMap</directive>
444 synchronization</description>
445 <syntax>RewriteLock <em>file-path</em></syntax>
446 <contextlist><context>server config</context></contextlist>
449 <p>This directive sets the filename for a synchronization
450 lockfile which mod_rewrite needs to communicate with <directive
451 module="mod_rewrite">RewriteMap</directive>
452 <em>programs</em>. Set this lockfile to a local path (not on a
453 NFS-mounted device) when you want to use a rewriting
454 map-program. It is not required for other types of rewriting
461 <name>RewriteMap</name>
462 <description>Defines a mapping function for key-lookup</description>
463 <syntax>RewriteMap <em>MapName</em> <em>MapType</em>:<em>MapSource</em>
465 <contextlist><context>server config</context><context>virtual host</context>
467 <compatibility>The choice of different dbm types is available in
468 Apache 2.0.41 and later</compatibility>
471 <p>The <directive>RewriteMap</directive> directive defines a
472 <em>Rewriting Map</em> which can be used inside rule
473 substitution strings by the mapping-functions to
474 insert/substitute fields through a key lookup. The source of
475 this lookup can be of various types.</p>
477 <p>The <a id="mapfunc" name="mapfunc"><em>MapName</em></a> is
478 the name of the map and will be used to specify a
479 mapping-function for the substitution strings of a rewriting
480 rule via one of the following constructs:</p>
483 <strong><code>${</code> <em>MapName</em> <code>:</code>
484 <em>LookupKey</em> <code>}</code><br />
485 <code>${</code> <em>MapName</em> <code>:</code>
486 <em>LookupKey</em> <code>|</code> <em>DefaultValue</em>
487 <code>}</code></strong>
490 <p>When such a construct occurs the map <em>MapName</em> is
491 consulted and the key <em>LookupKey</em> is looked-up. If the
492 key is found, the map-function construct is substituted by
493 <em>SubstValue</em>. If the key is not found then it is
494 substituted by <em>DefaultValue</em> or by the empty string
495 if no <em>DefaultValue</em> was specified.</p>
497 <p>The following combinations for <em>MapType</em> and
498 <em>MapSource</em> can be used:</p>
502 <strong>Standard Plain Text</strong><br />
503 MapType: <code>txt</code>, MapSource: Unix filesystem
504 path to valid regular file
506 <p>This is the standard rewriting map feature where the
507 <em>MapSource</em> is a plain ASCII file containing
508 either blank lines, comment lines (starting with a '#'
509 character) or pairs like the following - one per
513 <strong><em>MatchingKey</em>
514 <em>SubstValue</em></strong>
517 <example><title>Example</title>
520 ## map.txt -- rewriting map
523 Ralf.S.Engelschall rse # Bastard Operator From Hell
524 Mr.Joe.Average joe # Mr. Average
529 RewriteMap real-to-user txt:/path/to/file/map.txt
534 <strong>Randomized Plain Text</strong><br />
535 MapType: <code>rnd</code>, MapSource: Unix filesystem
536 path to valid regular file
538 <p>This is identical to the Standard Plain Text variant
539 above but with a special post-processing feature: After
540 looking up a value it is parsed according to contained
541 ``<code>|</code>'' characters which have the meaning of
542 ``or''. In other words they indicate a set of
543 alternatives from which the actual returned value is
544 chosen randomly. Although this sounds crazy and useless,
545 it was actually designed for load balancing in a reverse
546 proxy situation where the looked up values are server
552 ## map.txt -- rewriting map
555 static www1|www2|www3|www4
561 RewriteMap servers rnd:/path/to/file/map.txt
566 <strong>Hash File</strong><br /> MapType:
567 <code>dbm[=<em>type</em>]</code>, MapSource: Unix filesystem
568 path to valid regular file
570 <p>Here the source is a binary format DBM file containing
571 the same contents as a <em>Plain Text</em> format file, but
572 in a special representation which is optimized for really
573 fast lookups. The <em>type</em> can be sdbm, gdbm, ndbm, or
574 db depending on <a href="../install.html#dbm">compile-time
575 settings</a>. If the <em>type</em> is omitted, the
576 compile-time default will be chosen. You can create such a
577 file with any DBM tool or with the following Perl
578 script. Be sure to adjust it to create the appropriate
579 type of DBM. The example creates an NDBM file.</p>
585 ## txt2dbm -- convert txt map to dbm format
591 ($txtmap, $dbmmap) = @ARGV;
593 open(TXT, "<$txtmap") or die "Couldn't open $txtmap!\n";
594 tie (%DB, 'NDBM_File', $dbmmap,O_RDWR|O_TRUNC|O_CREAT, 0644)
595 or die "Couldn't create $dbmmap!\n";
597 while (<TXT>) {
598 next if (/^\s*#/ or /^\s*$/);
599 $DB{$1} = $2 if (/^\s*(\S+)\s+(\S+)/);
608 $ txt2dbm map.txt map.db
613 <strong>Internal Function</strong><br />
614 MapType: <code>int</code>, MapSource: Internal Apache
617 <p>Here the source is an internal Apache function.
618 Currently you cannot create your own, but the following
619 functions already exists:</p>
622 <li><strong>toupper</strong>:<br />
623 Converts the looked up key to all upper case.</li>
625 <li><strong>tolower</strong>:<br />
626 Converts the looked up key to all lower case.</li>
628 <li><strong>escape</strong>:<br />
629 Translates special characters in the looked up key to
632 <li><strong>unescape</strong>:<br />
633 Translates hex-encodings in the looked up key back to
634 special characters.</li>
639 <strong>External Rewriting Program</strong><br />
640 MapType: <code>prg</code>, MapSource: Unix filesystem
641 path to valid regular file
643 <p>Here the source is a program, not a map file. To
644 create it you can use the language of your choice, but
645 the result has to be a executable (<em>i.e.</em>, either
646 object-code or a script with the magic cookie trick
647 '<code>#!/path/to/interpreter</code>' as the first
650 <p>This program is started once at startup of the Apache
651 servers and then communicates with the rewriting engine
652 over its <code>stdin</code> and <code>stdout</code>
653 file-handles. For each map-function lookup it will
654 receive the key to lookup as a newline-terminated string
655 on <code>stdin</code>. It then has to give back the
656 looked-up value as a newline-terminated string on
657 <code>stdout</code> or the four-character string
658 ``<code>NULL</code>'' if it fails (<em>i.e.</em>, there
659 is no corresponding value for the given key). A trivial
660 program which will implement a 1:1 map (<em>i.e.</em>,
661 key == value) could be:</p>
667 while (<STDIN>) {
668 # ...put here any transformations or lookups...
674 <p>But be very careful:</p>
677 <li>``<em>Keep it simple, stupid</em>'' (KISS), because
678 if this program hangs it will hang the Apache server
679 when the rule occurs.</li>
681 <li>Avoid one common mistake: never do buffered I/O on
682 <code>stdout</code>! This will cause a deadloop! Hence
683 the ``<code>$|=1</code>'' in the above example...</li>
685 <li>Use the <directive
686 module="mod_rewrite">RewriteLock</directive> directive to
687 define a lockfile mod_rewrite can use to synchronize the
688 communication to the program. By default no such
689 synchronization takes place.</li>
693 <p>The <directive>RewriteMap</directive> directive can occur more than
694 once. For each mapping-function use one
695 <directive>RewriteMap</directive> directive to declare its rewriting
696 mapfile. While you cannot <strong>declare</strong> a map in
697 per-directory context it is of course possible to
698 <strong>use</strong> this map in per-directory context. </p>
700 <note><title>Note</title> For plain text and DBM format files the
701 looked-up keys are cached in-core until the <code>mtime</code> of the
702 mapfile changes or the server does a restart. This way you can have
703 map-functions in rules which are used for <strong>every</strong>
704 request. This is no problem, because the external lookup only happens
712 <name>RewriteBase</name>
713 <description>Sets the base URL for per-directory rewrites</description>
714 <syntax>RewriteBase <em>URL-path</em></syntax>
715 <default>See usage for information.</default>
716 <contextlist><context>directory</context><context>.htaccess</context>
718 <override>FileInfo</override>
721 <p>The <directive>RewriteBase</directive> directive explicitly
722 sets the base URL for per-directory rewrites. As you will see
723 below, <directive module="mod_rewrite">RewriteRule</directive>
724 can be used in per-directory config files
725 (<code>.htaccess</code>). There it will act locally,
726 <em>i.e.</em>, the local directory prefix is stripped at this
727 stage of processing and your rewriting rules act only on the
728 remainder. At the end it is automatically added back to the
729 path. The default setting is; <directive>RewriteBase</directive> <em>physical-directory-path</em></p>
731 <p>When a substitution occurs for a new URL, this module has
732 to re-inject the URL into the server processing. To be able
733 to do this it needs to know what the corresponding URL-prefix
734 or URL-base is. By default this prefix is the corresponding
735 filepath itself. <strong>But at most websites URLs are NOT
736 directly related to physical filename paths, so this
737 assumption will usually be wrong!</strong> There you have to
738 use the <code>RewriteBase</code> directive to specify the
739 correct URL-prefix.</p>
741 <note> If your webserver's URLs are <strong>not</strong> directly
742 related to physical file paths, you have to use
743 <directive>RewriteBase</directive> in every <code>.htaccess</code>
744 files where you want to use <directive
745 module="mod_rewrite">RewriteRule</directive> directives.
748 <p> For example, assume the following per-directory config file:</p>
753 # /abc/def/.htaccess -- per-dir config file for directory /abc/def
754 # Remember: /abc/def is the physical path of /xyz, <em>i.e.</em>, the server
755 # has a 'Alias /xyz /abc/def' directive <em>e.g.</em>
760 # let the server know that we were reached via /xyz and not
761 # via the physical path prefix /abc/def
764 # now the rewriting rules
765 RewriteRule ^oldstuff\.html$ newstuff.html
769 <p>In the above example, a request to
770 <code>/xyz/oldstuff.html</code> gets correctly rewritten to
771 the physical file <code>/abc/def/newstuff.html</code>.</p>
773 <note><title>For Apache Hackers</title>
774 <p>The following list gives detailed information about
775 the internal processing steps:</p>
781 /xyz/oldstuff.html -> /abc/def/oldstuff.html (per-server Alias)
782 /abc/def/oldstuff.html -> /abc/def/newstuff.html (per-dir RewriteRule)
783 /abc/def/newstuff.html -> /xyz/newstuff.html (per-dir RewriteBase)
784 /xyz/newstuff.html -> /abc/def/newstuff.html (per-server Alias)
787 /abc/def/newstuff.html
789 <p>This seems very complicated but is
790 the correct Apache internal processing, because the
791 per-directory rewriting comes too late in the
792 process. So, when it occurs the (rewritten) request
793 has to be re-injected into the Apache kernel! BUT:
794 While this seems like a serious overhead, it really
795 isn't, because this re-injection happens fully
796 internally to the Apache server and the same
797 procedure is used by many other operations inside
798 Apache. So, you can be sure the design and
799 implementation is correct.</p>
807 <name>RewriteCond</name>
808 <description>Defines a condition under which rewriting will take place
811 <em>TestString</em> <em>CondPattern</em></syntax>
812 <contextlist><context>server config</context><context>virtual host</context>
813 <context>directory</context><context>.htaccess</context></contextlist>
814 <override>FileInfo</override>
817 <p>The <directive>RewriteCond</directive> directive defines a
818 rule condition. Precede a <directive
819 module="mod_rewrite">RewriteRule</directive> directive with one
820 or more <directive>RewriteCond</directive> directives. The following
821 rewriting rule is only used if its pattern matches the current
822 state of the URI <strong>and</strong> if these additional
823 conditions apply too.</p>
825 <p><em>TestString</em> is a string which can contains the
826 following expanded constructs in addition to plain text:</p>
830 <strong>RewriteRule backreferences</strong>: These are
831 backreferences of the form
834 <strong><code>$N</code></strong>
836 (0 <= N <= 9) which provide access to the grouped
837 parts (parenthesis!) of the pattern from the
838 corresponding <code>RewriteRule</code> directive (the one
839 following the current bunch of <code>RewriteCond</code>
844 <strong>RewriteCond backreferences</strong>: These are
845 backreferences of the form
848 <strong><code>%N</code></strong>
850 (1 <= N <= 9) which provide access to the grouped
851 parts (parentheses!) of the pattern from the last matched
852 <code>RewriteCond</code> directive in the current bunch
857 <strong>RewriteMap expansions</strong>: These are
858 expansions of the form
861 <strong><code>${mapname:key|default}</code></strong>
863 See <a href="#mapfunc">the documentation for
864 RewriteMap</a> for more details.
868 <strong>Server-Variables</strong>: These are variables of
872 <strong><code>%{</code> <em>NAME_OF_VARIABLE</em>
873 <code>}</code></strong>
875 where <em>NAME_OF_VARIABLE</em> can be a string taken
876 from the following list:
880 <th>HTTP headers:</th> <th>connection & request:</th> <th></th>
885 HTTP_USER_AGENT<br />
890 HTTP_PROXY_CONNECTION<br />
901 SCRIPT_FILENAME<br />
911 <th>server internals:</th> <th>system stuff:</th> <th>specials:</th>
921 SERVER_PROTOCOL<br />
922 SERVER_SOFTWARE<br />
940 REQUEST_FILENAME<br />
948 <p>These variables all
949 correspond to the similarly named HTTP
950 MIME-headers, C variables of the Apache server or
951 <code>struct tm</code> fields of the Unix system.
952 Most are documented elsewhere in the Manual or in
953 the CGI specification. Those that are special to
954 mod_rewrite include:</p>
957 <dt><code>IS_SUBREQ</code></dt>
959 <dd>Will contain the text "true" if the request
960 currently being processed is a sub-request,
961 "false" otherwise. Sub-requests may be generated
962 by modules that need to resolve additional files
963 or URIs in order to complete their tasks.</dd>
965 <dt><code>API_VERSION</code></dt>
967 <dd>This is the version of the Apache module API
968 (the internal interface between server and
969 module) in the current httpd build, as defined in
970 include/ap_mmn.h. The module API version
971 corresponds to the version of Apache in use (in
972 the release version of Apache 1.3.14, for
973 instance, it is 19990320:10), but is mainly of
974 interest to module authors.</dd>
976 <dt><code>THE_REQUEST</code></dt>
978 <dd>The full HTTP request line sent by the
979 browser to the server (e.g., "<code>GET
980 /index.html HTTP/1.1</code>"). This does not
981 include any additional headers sent by the
984 <dt><code>REQUEST_URI</code></dt>
986 <dd>The resource requested in the HTTP request
987 line. (In the example above, this would be
990 <dt><code>REQUEST_FILENAME</code></dt>
992 <dd>The full local filesystem path to the file or
993 script matching the request.</dd>
995 <dt><code>HTTPS</code></dt>
997 <dd>Will contain the text "on" if the connection is
998 using SSL/TLS, or "off" otherwise. (This variable
999 can be safely used regardless of whether
1000 <module>mod_ssl</module> is loaded).</dd>
1007 <p>Special Notes:</p>
1010 <li>The variables SCRIPT_FILENAME and REQUEST_FILENAME
1011 contain the same value, <em>i.e.</em>, the value of the
1012 <code>filename</code> field of the internal
1013 <code>request_rec</code> structure of the Apache server.
1014 The first name is just the commonly known CGI variable name
1015 while the second is the consistent counterpart to
1016 REQUEST_URI (which contains the value of the
1017 <code>uri</code> field of <code>request_rec</code>).</li>
1019 <li>There is the special format:
1020 <code>%{ENV:variable}</code> where <em>variable</em> can be
1021 any environment variable. This is looked-up via internal
1022 Apache structures and (if not found there) via
1023 <code>getenv()</code> from the Apache server process.</li>
1025 <li>There is the special format:
1026 <code>%{SSL:variable}</code> where <em>variable</em> is the
1027 name of an <a href="mod_ssl.html#envvars">SSL environment
1028 variable</a>; this can be used whether or not
1029 <module>mod_ssl</module> is loaded, but will always expand to
1030 the empty string if it is not. Example:
1031 <code>%{SSL:SSL_CIPHER_USEKEYSIZE}</code> may expand to
1032 <code>128</code>.</li>
1034 <li>There is the special format:
1035 <code>%{HTTP:header}</code> where <em>header</em> can be
1036 any HTTP MIME-header name. This is looked-up from the HTTP
1037 request. Example: <code>%{HTTP:Proxy-Connection}</code> is
1038 the value of the HTTP header
1039 ``<code>Proxy-Connection:</code>''.</li>
1041 <li>There is the special format
1042 <code>%{LA-U:variable}</code> for look-aheads which perform
1043 an internal (URL-based) sub-request to determine the final
1044 value of <em>variable</em>. Use this when you want to use a
1045 variable for rewriting which is actually set later in an
1046 API phase and thus is not available at the current stage.
1047 For instance when you want to rewrite according to the
1048 <code>REMOTE_USER</code> variable from within the
1049 per-server context (<code>httpd.conf</code> file) you have
1050 to use <code>%{LA-U:REMOTE_USER}</code> because this
1051 variable is set by the authorization phases which come
1052 <em>after</em> the URL translation phase where mod_rewrite
1053 operates. On the other hand, because mod_rewrite implements
1054 its per-directory context (<code>.htaccess</code> file) via
1055 the Fixup phase of the API and because the authorization
1056 phases come <em>before</em> this phase, you just can use
1057 <code>%{REMOTE_USER}</code> there.</li>
1059 <li>There is the special format:
1060 <code>%{LA-F:variable}</code> which performs an internal
1061 (filename-based) sub-request to determine the final value
1062 of <em>variable</em>. Most of the time this is the same as
1066 <p><em>CondPattern</em> is the condition pattern,
1067 <em>i.e.</em>, a regular expression which is applied to the
1068 current instance of the <em>TestString</em>, <em>i.e.</em>,
1069 <em>TestString</em> is evaluated and then matched against
1070 <em>CondPattern</em>.</p>
1072 <p><strong>Remember:</strong> <em>CondPattern</em> is a
1073 <em>perl compatible regular expression</em> with some
1077 <li>You can prefix the pattern string with a
1078 '<code>!</code>' character (exclamation mark) to specify a
1079 <strong>non</strong>-matching pattern.</li>
1082 There are some special variants of <em>CondPatterns</em>.
1083 Instead of real regular expression strings you can also
1084 use one of the following:
1087 <li>'<strong><CondPattern</strong>' (is lexically
1089 Treats the <em>CondPattern</em> as a plain string and
1090 compares it lexically to <em>TestString</em>. True if
1091 <em>TestString</em> is lexically lower than
1092 <em>CondPattern</em>.</li>
1094 <li>'<strong>>CondPattern</strong>' (is lexically
1096 Treats the <em>CondPattern</em> as a plain string and
1097 compares it lexically to <em>TestString</em>. True if
1098 <em>TestString</em> is lexically greater than
1099 <em>CondPattern</em>.</li>
1101 <li>'<strong>=CondPattern</strong>' (is lexically
1103 Treats the <em>CondPattern</em> as a plain string and
1104 compares it lexically to <em>TestString</em>. True if
1105 <em>TestString</em> is lexically equal to
1106 <em>CondPattern</em>, i.e the two strings are exactly
1107 equal (character by character). If <em>CondPattern</em>
1108 is just <code>""</code> (two quotation marks) this
1109 compares <em>TestString</em> to the empty string.</li>
1111 <li>'<strong>-d</strong>' (is
1112 <strong>d</strong>irectory)<br />
1113 Treats the <em>TestString</em> as a pathname and tests
1114 if it exists and is a directory.</li>
1116 <li>'<strong>-f</strong>' (is regular
1117 <strong>f</strong>ile)<br />
1118 Treats the <em>TestString</em> as a pathname and tests
1119 if it exists and is a regular file.</li>
1121 <li>'<strong>-s</strong>' (is regular file with
1122 <strong>s</strong>ize)<br />
1123 Treats the <em>TestString</em> as a pathname and tests
1124 if it exists and is a regular file with size greater
1127 <li>'<strong>-l</strong>' (is symbolic
1128 <strong>l</strong>ink)<br />
1129 Treats the <em>TestString</em> as a pathname and tests
1130 if it exists and is a symbolic link.</li>
1132 <li>'<strong>-x</strong>' (has e<strong>x</strong>ecutable
1134 Treats the <em>TestString</em> as a pathname and tests
1135 if it exists and has execution permissions. These permissions
1136 are determined depending on the underlying OS.</li>
1138 <li>'<strong>-F</strong>' (is existing file via
1140 Checks if <em>TestString</em> is a valid file and
1141 accessible via all the server's currently-configured
1142 access controls for that path. This uses an internal
1143 subrequest to determine the check, so use it with care
1144 because it decreases your servers performance!</li>
1146 <li>'<strong>-U</strong>' (is existing URL via
1148 Checks if <em>TestString</em> is a valid URL and
1149 accessible via all the server's currently-configured
1150 access controls for that path. This uses an internal
1151 subrequest to determine the check, so use it with care
1152 because it decreases your server's performance!</li>
1155 <note><title>Notice</title>
1156 All of these tests can
1157 also be prefixed by an exclamation mark ('!') to
1158 negate their meaning.
1163 <p>Additionally you can set special flags for
1164 <em>CondPattern</em> by appending</p>
1167 <strong><code>[</code><em>flags</em><code>]</code></strong>
1170 <p>as the third argument to the <code>RewriteCond</code>
1171 directive. <em>Flags</em> is a comma-separated list of the
1172 following flags:</p>
1175 <li>'<strong><code>nocase|NC</code></strong>'
1176 (<strong>n</strong>o <strong>c</strong>ase)<br />
1177 This makes the test case-insensitive, <em>i.e.</em>, there
1178 is no difference between 'A-Z' and 'a-z' both in the
1179 expanded <em>TestString</em> and the <em>CondPattern</em>.
1180 This flag is effective only for comparisons between
1181 <em>TestString</em> and <em>CondPattern</em>. It has no
1182 effect on filesystem and subrequest checks.</li>
1185 '<strong><code>ornext|OR</code></strong>'
1186 (<strong>or</strong> next condition)<br />
1187 Use this to combine rule conditions with a local OR
1188 instead of the implicit AND. Typical example:
1192 RewriteCond %{REMOTE_HOST} ^host1.* [OR]
1193 RewriteCond %{REMOTE_HOST} ^host2.* [OR]
1194 RewriteCond %{REMOTE_HOST} ^host3.*
1195 RewriteRule ...some special stuff for any of these hosts...
1199 Without this flag you would have to write the cond/rule
1204 <p><strong>Example:</strong></p>
1206 <p>To rewrite the Homepage of a site according to the
1207 ``<code>User-Agent:</code>'' header of the request, you can
1208 use the following: </p>
1212 RewriteCond %{HTTP_USER_AGENT} ^Mozilla.*
1213 RewriteRule ^/$ /homepage.max.html [L]
1215 RewriteCond %{HTTP_USER_AGENT} ^Lynx.*
1216 RewriteRule ^/$ /homepage.min.html [L]
1218 RewriteRule ^/$ /homepage.std.html [L]
1222 <p>Interpretation: If you use Netscape Navigator as your
1223 browser (which identifies itself as 'Mozilla'), then you
1224 get the max homepage, which includes Frames, <em>etc.</em>
1225 If you use the Lynx browser (which is Terminal-based), then
1226 you get the min homepage, which contains no images, no
1227 tables, <em>etc.</em> If you use any other browser you get
1228 the standard homepage.</p>
1232 </directivesynopsis>
1235 <name>RewriteRule</name>
1236 <description>Defines rules for the rewriting engine</description>
1238 <em>Pattern</em> <em>Substitution</em></syntax>
1239 <contextlist><context>server config</context><context>virtual host</context>
1240 <context>directory</context><context>.htaccess</context></contextlist>
1241 <override>FileInfo</override>
1242 <compatibility>The cookie-flag is available in Apache 2.0.40 and later.</compatibility>
1245 <p>The <directive>RewriteRule</directive> directive is the real
1246 rewriting workhorse. The directive can occur more than once.
1247 Each directive then defines one single rewriting rule. The
1248 <strong>definition order</strong> of these rules is
1249 <strong>important</strong>, because this order is used when
1250 applying the rules at run-time.</p>
1252 <p><a id="patterns" name="patterns"><em>Pattern</em></a> is
1253 a perl compatible <a id="regexp" name="regexp">regular
1254 expression</a> which gets applied to the current URL. Here
1255 ``current'' means the value of the URL when this rule gets
1256 applied. This may not be the originally requested URL,
1257 because any number of rules may already have matched and made
1258 alterations to it.</p>
1260 <p>Some hints about the syntax of regular expressions:</p>
1263 <strong>Text:</strong>
1264 <strong><code>.</code></strong> Any single character
1265 <strong><code>[</code></strong>chars<strong><code>]</code></strong> Character class: One of chars
1266 <strong><code>[^</code></strong>chars<strong><code>]</code></strong> Character class: None of chars
1267 text1<strong><code>|</code></strong>text2 Alternative: text1 or text2
1269 <strong>Quantifiers:</strong>
1270 <strong><code>?</code></strong> 0 or 1 of the preceding text
1271 <strong><code>*</code></strong> 0 or N of the preceding text (N > 0)
1272 <strong><code>+</code></strong> 1 or N of the preceding text (N > 1)
1274 <strong>Grouping:</strong>
1275 <strong><code>(</code></strong>text<strong><code>)</code></strong> Grouping of text
1276 (either to set the borders of an alternative or
1277 for making backreferences where the <strong>N</strong>th group can
1278 be used on the RHS of a RewriteRule with <code>$</code><strong>N</strong>)
1280 <strong>Anchors:</strong>
1281 <strong><code>^</code></strong> Start of line anchor
1282 <strong><code>$</code></strong> End of line anchor
1284 <strong>Escaping:</strong>
1285 <strong><code>\</code></strong>char escape that particular char
1286 (for instance to specify the chars "<code>.[]()</code>" <em>etc.</em>)
1289 <p>For more information about regular expressions have a look at the
1290 perl regular expression manpage ("<a
1291 href="http://www.perldoc.com/perl5.6.1/pod/perlre.html">perldoc
1292 perlre</a>"). If you are interested in more detailed
1293 information about regular expressions and their variants
1294 (POSIX regex <em>etc.</em>) have a look at the
1295 following dedicated book on this topic:</p>
1298 <em>Mastering Regular Expressions</em><br />
1299 Jeffrey E.F. Friedl<br />
1300 Nutshell Handbook Series<br />
1301 O'Reilly & Associates, Inc. 1997<br />
1302 ISBN 1-56592-257-3<br />
1305 <p>Additionally in mod_rewrite the NOT character
1306 ('<code>!</code>') is a possible pattern prefix. This gives
1307 you the ability to negate a pattern; to say, for instance:
1308 ``<em>if the current URL does <strong>NOT</strong> match this
1309 pattern</em>''. This can be used for exceptional cases, where
1310 it is easier to match the negative pattern, or as a last
1313 <note><title>Notice</title>
1314 When using the NOT character
1315 to negate a pattern you cannot have grouped wildcard
1316 parts in the pattern. This is impossible because when the
1317 pattern does NOT match, there are no contents for the
1318 groups. In consequence, if negated patterns are used, you
1319 cannot use <code>$N</code> in the substitution
1323 <p><a id="rhs" name="rhs"><em>Substitution</em></a> of a
1324 rewriting rule is the string which is substituted for (or
1325 replaces) the original URL for which <em>Pattern</em>
1326 matched. Beside plain text you can use</p>
1329 <li>back-references <code>$N</code> to the RewriteRule
1332 <li>back-references <code>%N</code> to the last matched
1333 RewriteCond pattern</li>
1335 <li>server-variables as in rule condition test-strings
1336 (<code>%{VARNAME}</code>)</li>
1338 <li><a href="#mapfunc">mapping-function</a> calls
1339 (<code>${mapname:key|default}</code>)</li>
1341 <p>Back-references are <code>$</code><strong>N</strong>
1342 (<strong>N</strong>=0..9) identifiers which will be replaced
1343 by the contents of the <strong>N</strong>th group of the
1344 matched <em>Pattern</em>. The server-variables are the same
1345 as for the <em>TestString</em> of a <code>RewriteCond</code>
1346 directive. The mapping-functions come from the
1347 <code>RewriteMap</code> directive and are explained there.
1348 These three types of variables are expanded in the order of
1349 the above list. </p>
1351 <p>As already mentioned above, all the rewriting rules are
1352 applied to the <em>Substitution</em> (in the order of
1353 definition in the config file). The URL is <strong>completely
1354 replaced</strong> by the <em>Substitution</em> and the
1355 rewriting process goes on until there are no more rules
1356 unless explicitly terminated by a
1357 <code><strong>L</strong></code> flag - see below.</p>
1359 <p>There is a special substitution string named
1360 '<code>-</code>' which means: <strong>NO
1361 substitution</strong>! Sounds silly? No, it is useful to
1362 provide rewriting rules which <strong>only</strong> match
1363 some URLs but do no substitution, <em>e.g.</em>, in
1364 conjunction with the <strong>C</strong> (chain) flag to be
1365 able to have more than one pattern to be applied before a
1366 substitution occurs.</p>
1368 <p>One more note: You can even create URLs in the
1369 substitution string containing a query string part. Just use
1370 a question mark inside the substitution string to indicate
1371 that the following stuff should be re-injected into the
1372 QUERY_STRING. When you want to erase an existing query
1373 string, end the substitution string with just the question
1376 <note><title>Note</title>
1377 There is a special feature:
1378 When you prefix a substitution field with
1379 <code>http://</code><em>thishost</em>[<em>:thisport</em>]
1380 then <strong>mod_rewrite</strong> automatically strips it
1381 out. This auto-reduction on implicit external redirect
1382 URLs is a useful and important feature when used in
1383 combination with a mapping-function which generates the
1384 hostname part. Have a look at the first example in the
1385 example section below to understand this.
1388 <note><title>Remember</title>
1389 An unconditional external
1390 redirect to your own server will not work with the prefix
1391 <code>http://thishost</code> because of this feature. To
1392 achieve such a self-redirect, you have to use the
1393 <strong>R</strong>-flag (see below).
1396 <p>Additionally you can set special flags for
1397 <em>Substitution</em> by appending</p>
1400 <strong><code>[</code><em>flags</em><code>]</code></strong>
1403 as the third argument to the <code>RewriteRule</code>
1404 directive. <em>Flags</em> is a comma-separated list of the
1405 following flags: </p>
1409 '<strong><code>redirect|R</code>
1410 [=<em>code</em>]</strong>' (force <a id="redirect"
1411 name="redirect"><strong>r</strong>edirect</a>)<br />
1412 Prefix <em>Substitution</em> with
1413 <code>http://thishost[:thisport]/</code> (which makes the
1414 new URL a URI) to force a external redirection. If no
1415 <em>code</em> is given a HTTP response of 302 (MOVED
1416 TEMPORARILY) is used. If you want to use other response
1417 codes in the range 300-400 just specify them as a number
1418 or use one of the following symbolic names:
1419 <code>temp</code> (default), <code>permanent</code>,
1420 <code>seeother</code>. Use it for rules which should
1421 canonicalize the URL and give it back to the client,
1422 <em>e.g.</em>, translate ``<code>/~</code>'' into
1423 ``<code>/u/</code>'' or always append a slash to
1424 <code>/u/</code><em>user</em>, etc.<br />
1427 <p><strong>Note:</strong> When you use this flag, make
1428 sure that the substitution field is a valid URL! If not,
1429 you are redirecting to an invalid location! And remember
1430 that this flag itself only prefixes the URL with
1431 <code>http://thishost[:thisport]/</code>, rewriting
1432 continues. Usually you also want to stop and do the
1433 redirection immediately. To stop the rewriting you also
1434 have to provide the 'L' flag.</p>
1437 <li>'<strong><code>forbidden|F</code></strong>' (force URL
1438 to be <strong>f</strong>orbidden)<br />
1439 This forces the current URL to be forbidden,
1440 <em>i.e.</em>, it immediately sends back a HTTP response of
1441 403 (FORBIDDEN). Use this flag in conjunction with
1442 appropriate RewriteConds to conditionally block some
1445 <li>'<strong><code>gone|G</code></strong>' (force URL to be
1446 <strong>g</strong>one)<br />
1447 This forces the current URL to be gone, <em>i.e.</em>, it
1448 immediately sends back a HTTP response of 410 (GONE). Use
1449 this flag to mark pages which no longer exist as gone.</li>
1452 '<strong><code>proxy|P</code></strong>' (force
1453 <strong>p</strong>roxy)<br />
1454 This flag forces the substitution part to be internally
1455 forced as a proxy request and immediately (<em>i.e.</em>,
1456 rewriting rule processing stops here) put through the <a
1457 href="mod_proxy.html">proxy module</a>. You have to make
1458 sure that the substitution string is a valid URI
1459 (<em>e.g.</em>, typically starting with
1460 <code>http://</code><em>hostname</em>) which can be
1461 handled by the Apache proxy module. If not you get an
1462 error from the proxy module. Use this flag to achieve a
1463 more powerful implementation of the <a
1464 href="mod_proxy.html#proxypass">ProxyPass</a> directive,
1465 to map some remote stuff into the namespace of the local
1468 <p>Notice: To use this functionality make sure you have
1469 the proxy module compiled into your Apache server
1470 program. If you don't know please check whether
1471 <code>mod_proxy.c</code> is part of the ``<code>httpd
1472 -l</code>'' output. If yes, this functionality is
1473 available to mod_rewrite. If not, then you first have to
1474 rebuild the ``<code>httpd</code>'' program with mod_proxy
1478 <li>'<strong><code>last|L</code></strong>'
1479 (<strong>l</strong>ast rule)<br />
1480 Stop the rewriting process here and don't apply any more
1481 rewriting rules. This corresponds to the Perl
1482 <code>last</code> command or the <code>break</code> command
1483 from the C language. Use this flag to prevent the currently
1484 rewritten URL from being rewritten further by following
1485 rules. For example, use it to rewrite the root-path URL
1486 ('<code>/</code>') to a real one, <em>e.g.</em>,
1487 '<code>/e/www/</code>'.</li>
1489 <li>'<strong><code>next|N</code></strong>'
1490 (<strong>n</strong>ext round)<br />
1491 Re-run the rewriting process (starting again with the
1492 first rewriting rule). Here the URL to match is again not
1493 the original URL but the URL from the last rewriting rule.
1494 This corresponds to the Perl <code>next</code> command or
1495 the <code>continue</code> command from the C language. Use
1496 this flag to restart the rewriting process, <em>i.e.</em>,
1497 to immediately go to the top of the loop.<br />
1498 <strong>But be careful not to create an infinite
1501 <li>'<strong><code>chain|C</code></strong>'
1502 (<strong>c</strong>hained with next rule)<br />
1503 This flag chains the current rule with the next rule
1504 (which itself can be chained with the following rule,
1505 <em>etc.</em>). This has the following effect: if a rule
1506 matches, then processing continues as usual, <em>i.e.</em>,
1507 the flag has no effect. If the rule does
1508 <strong>not</strong> match, then all following chained
1509 rules are skipped. For instance, use it to remove the
1510 ``<code>.www</code>'' part inside a per-directory rule set
1511 when you let an external redirect happen (where the
1512 ``<code>.www</code>'' part should not to occur!).</li>
1515 '<strong><code>type|T</code></strong>=<em>MIME-type</em>'
1516 (force MIME <strong>t</strong>ype)<br />
1517 Force the MIME-type of the target file to be
1518 <em>MIME-type</em>. For instance, this can be used to
1519 setup the content-type based on some conditions.
1520 For example, the following snippet allows <code>.php</code> files to
1521 be <em>displayed</em> by <code>mod_php</code> if they are called with
1522 the <code>.phps</code> extension:
1524 RewriteRule ^(.+\.php)s$ $1 [T=application/x-httpd-php-source]
1529 '<strong><code>handler|H</code></strong>=<em>Content-handler</em>'
1530 (force Content <strong>h</strong>andler)<br />
1531 Force the Content-handler of the target file to be
1532 <em>Content-handler</em>. For instance, this can be used to
1533 simulate the <code>mod_alias</code> directive
1534 <code>ScriptAlias</code> which internally forces all files
1535 inside the mapped directory to have a handler of
1536 ``<code>cgi-script</code>''.</li>
1539 '<strong><code>nosubreq|NS</code></strong>' (used only if
1540 <strong>n</strong>o internal
1541 <strong>s</strong>ub-request)<br />
1542 This flag forces the rewriting engine to skip a
1543 rewriting rule if the current request is an internal
1544 sub-request. For instance, sub-requests occur internally
1545 in Apache when <code>mod_include</code> tries to find out
1546 information about possible directory default files
1547 (<code>index.xxx</code>). On sub-requests it is not
1548 always useful and even sometimes causes a failure to if
1549 the complete set of rules are applied. Use this flag to
1550 exclude some rules.<br />
1553 <p>Use the following rule for your decision: whenever you
1554 prefix some URLs with CGI-scripts to force them to be
1555 processed by the CGI-script, the chance is high that you
1556 will run into problems (or even overhead) on
1557 sub-requests. In these cases, use this flag.</p>
1560 <li>'<strong><code>nocase|NC</code></strong>'
1561 (<strong>n</strong>o <strong>c</strong>ase)<br />
1562 This makes the <em>Pattern</em> case-insensitive,
1563 <em>i.e.</em>, there is no difference between 'A-Z' and
1564 'a-z' when <em>Pattern</em> is matched against the current
1567 <li>'<strong><code>qsappend|QSA</code></strong>'
1568 (<strong>q</strong>uery <strong>s</strong>tring
1569 <strong>a</strong>ppend)<br />
1570 This flag forces the rewriting engine to append a query
1571 string part in the substitution string to the existing one
1572 instead of replacing it. Use this when you want to add more
1573 data to the query string via a rewrite rule.</li>
1576 '<strong><code>noescape|NE</code></strong>'
1577 (<strong>n</strong>o URI <strong>e</strong>scaping of
1579 This flag keeps mod_rewrite from applying the usual URI
1580 escaping rules to the result of a rewrite. Ordinarily,
1581 special characters (such as '%', '$', ';', and so on)
1582 will be escaped into their hexcode equivalents ('%25',
1583 '%24', and '%3B', respectively); this flag prevents this
1584 from being done. This allows percent symbols to appear in
1587 RewriteRule /foo/(.*) /bar?arg=P1\%3d$1 [R,NE]
1590 which would turn '<code>/foo/zed</code>' into a safe
1591 request for '<code>/bar?arg=P1=zed</code>'.
1595 '<strong><code>passthrough|PT</code></strong>'
1596 (<strong>p</strong>ass <strong>t</strong>hrough to next
1598 This flag forces the rewriting engine to set the
1599 <code>uri</code> field of the internal
1600 <code>request_rec</code> structure to the value of the
1601 <code>filename</code> field. This flag is just a hack to
1602 be able to post-process the output of
1603 <code>RewriteRule</code> directives by
1604 <code>Alias</code>, <code>ScriptAlias</code>,
1605 <code>Redirect</code>, <em>etc.</em> directives from
1606 other URI-to-filename translators. A trivial example to
1607 show the semantics: If you want to rewrite
1608 <code>/abc</code> to <code>/def</code> via the rewriting
1609 engine of <code>mod_rewrite</code> and then
1610 <code>/def</code> to <code>/ghi</code> with
1611 <code>mod_alias</code>:
1613 RewriteRule ^/abc(.*) /def$1 [PT]<br />
1616 If you omit the <code>PT</code> flag then
1617 <code>mod_rewrite</code> will do its job fine,
1618 <em>i.e.</em>, it rewrites <code>uri=/abc/...</code> to
1619 <code>filename=/def/...</code> as a full API-compliant
1620 URI-to-filename translator should do. Then
1621 <code>mod_alias</code> comes and tries to do a
1622 URI-to-filename transition which will not work.
1624 <p>Note: <strong>You have to use this flag if you want to
1625 intermix directives of different modules which contain
1626 URL-to-filename translators</strong>. The typical example
1627 is the use of <code>mod_alias</code> and
1628 <code>mod_rewrite</code>..</p>
1631 <li>'<strong><code>skip|S</code></strong>=<em>num</em>'
1632 (<strong>s</strong>kip next rule(s))<br />
1633 This flag forces the rewriting engine to skip the next
1634 <em>num</em> rules in sequence when the current rule
1635 matches. Use this to make pseudo if-then-else constructs:
1636 The last rule of the then-clause becomes
1637 <code>skip=N</code> where N is the number of rules in the
1638 else-clause. (This is <strong>not</strong> the same as the
1639 'chain|C' flag!)</li>
1642 '<strong><code>env|E=</code></strong><em>VAR</em>:<em>VAL</em>'
1643 (set <strong>e</strong>nvironment variable)<br />
1644 This forces an environment variable named <em>VAR</em> to
1645 be set to the value <em>VAL</em>, where <em>VAL</em> can
1646 contain regexp backreferences <code>$N</code> and
1647 <code>%N</code> which will be expanded. You can use this
1648 flag more than once to set more than one variable. The
1649 variables can be later dereferenced in many situations, but
1650 usually from within XSSI (via <code><!--#echo
1651 var="VAR"--></code>) or CGI (<em>e.g.</em>
1652 <code>$ENV{'VAR'}</code>). Additionally you can dereference
1653 it in a following RewriteCond pattern via
1654 <code>%{ENV:VAR}</code>. Use this to strip but remember
1655 information from URLs.</li>
1658 '<strong><code>cookie|CO=</code></strong><em>NAME</em>:<em>VAL</em>:<em>domain</em>[:<em>lifetime</em>[:<em>path</em>]]'
1659 (set <strong>co</strong>okie)<br />
1660 This sets a cookie on the client's browser. The cookie's name
1661 is specified by <em>NAME</em> and the value is
1662 <em>VAL</em>. The <em>domain</em> field is the domain of the
1663 cookie, such as '.apache.org',the optional <em>lifetime</em>
1664 is the lifetime of the cookie in minutes, and the optional
1665 <em>path</em> is the path of the cookie</li>
1669 <note><title>Note</title> Never forget that <em>Pattern</em> is
1670 applied to a complete URL in per-server configuration
1671 files. <strong>But in per-directory configuration files, the
1672 per-directory prefix (which always is the same for a specific
1673 directory!) is automatically <em>removed</em> for the pattern matching
1674 and automatically <em>added</em> after the substitution has been
1675 done.</strong> This feature is essential for many sorts of rewriting,
1676 because without this prefix stripping you have to match the parent
1677 directory which is not always possible.
1679 <p>There is one exception: If a substitution string
1680 starts with ``<code>http://</code>'' then the directory
1681 prefix will <strong>not</strong> be added and an
1682 external redirect or proxy throughput (if flag
1683 <strong>P</strong> is used!) is forced!</p>
1686 <note><title>Note</title>
1687 To enable the rewriting engine
1688 for per-directory configuration files you need to set
1689 ``<code>RewriteEngine On</code>'' in these files
1690 <strong>and</strong> ``<code>Options
1691 FollowSymLinks</code>'' must be enabled. If your
1692 administrator has disabled override of
1693 <code>FollowSymLinks</code> for a user's directory, then
1694 you cannot use the rewriting engine. This restriction is
1695 needed for security reasons.
1698 <p>Here are all possible substitution combinations and their
1701 <p><strong>Inside per-server configuration
1702 (<code>httpd.conf</code>)<br />
1703 for request ``<code>GET
1704 /somepath/pathinfo</code>'':</strong><br />
1708 <strong>Given Rule</strong> <strong>Resulting Substitution</strong>
1709 ---------------------------------------------- ----------------------------------
1710 ^/somepath(.*) otherpath$1 not supported, because invalid!
1712 ^/somepath(.*) otherpath$1 [R] not supported, because invalid!
1714 ^/somepath(.*) otherpath$1 [P] not supported, because invalid!
1715 ---------------------------------------------- ----------------------------------
1716 ^/somepath(.*) /otherpath$1 /otherpath/pathinfo
1718 ^/somepath(.*) /otherpath$1 [R] http://thishost/otherpath/pathinfo
1719 via external redirection
1721 ^/somepath(.*) /otherpath$1 [P] not supported, because silly!
1722 ---------------------------------------------- ----------------------------------
1723 ^/somepath(.*) http://thishost/otherpath$1 /otherpath/pathinfo
1725 ^/somepath(.*) http://thishost/otherpath$1 [R] http://thishost/otherpath/pathinfo
1726 via external redirection
1728 ^/somepath(.*) http://thishost/otherpath$1 [P] not supported, because silly!
1729 ---------------------------------------------- ----------------------------------
1730 ^/somepath(.*) http://otherhost/otherpath$1 http://otherhost/otherpath/pathinfo
1731 via external redirection
1733 ^/somepath(.*) http://otherhost/otherpath$1 [R] http://otherhost/otherpath/pathinfo
1734 via external redirection
1735 (the [R] flag is redundant)
1737 ^/somepath(.*) http://otherhost/otherpath$1 [P] http://otherhost/otherpath/pathinfo
1741 <p><strong>Inside per-directory configuration for
1742 <code>/somepath</code><br />
1743 (<em>i.e.</em>, file <code>.htaccess</code> in dir
1744 <code>/physical/path/to/somepath</code> containing
1745 <code>RewriteBase /somepath</code>)<br />
1746 for request ``<code>GET
1747 /somepath/localpath/pathinfo</code>'':</strong><br />
1751 <strong>Given Rule</strong> <strong>Resulting Substitution</strong>
1752 ---------------------------------------------- ----------------------------------
1753 ^localpath(.*) otherpath$1 /somepath/otherpath/pathinfo
1755 ^localpath(.*) otherpath$1 [R] http://thishost/somepath/otherpath/pathinfo
1756 via external redirection
1758 ^localpath(.*) otherpath$1 [P] not supported, because silly!
1759 ---------------------------------------------- ----------------------------------
1760 ^localpath(.*) /otherpath$1 /otherpath/pathinfo
1762 ^localpath(.*) /otherpath$1 [R] http://thishost/otherpath/pathinfo
1763 via external redirection
1765 ^localpath(.*) /otherpath$1 [P] not supported, because silly!
1766 ---------------------------------------------- ----------------------------------
1767 ^localpath(.*) http://thishost/otherpath$1 /otherpath/pathinfo
1769 ^localpath(.*) http://thishost/otherpath$1 [R] http://thishost/otherpath/pathinfo
1770 via external redirection
1772 ^localpath(.*) http://thishost/otherpath$1 [P] not supported, because silly!
1773 ---------------------------------------------- ----------------------------------
1774 ^localpath(.*) http://otherhost/otherpath$1 http://otherhost/otherpath/pathinfo
1775 via external redirection
1777 ^localpath(.*) http://otherhost/otherpath$1 [R] http://otherhost/otherpath/pathinfo
1778 via external redirection
1779 (the [R] flag is redundant)
1781 ^localpath(.*) http://otherhost/otherpath$1 [P] http://otherhost/otherpath/pathinfo
1785 <p><strong>Example:</strong></p>
1787 <p>We want to rewrite URLs of the form </p>
1790 <code>/</code> <em>Language</em> <code>/~</code>
1791 <em>Realname</em> <code>/.../</code> <em>File</em>
1797 <code>/u/</code> <em>Username</em> <code>/.../</code>
1798 <em>File</em> <code>.</code> <em>Language</em>
1801 <p>We take the rewrite mapfile from above and save it under
1802 <code>/path/to/file/map.txt</code>. Then we only have to
1803 add the following lines to the Apache server configuration
1808 RewriteLog /path/to/file/rewrite.log
1809 RewriteMap real-to-user txt:/path/to/file/map.txt
1810 RewriteRule ^/([^/]+)/~([^/]+)/(.*)$ /u/${real-to-user:$2|nobody}/$3.$1
1814 </directivesynopsis>