The
httpd.conf or in .htaccess. The path generated
by a rewrite rule can include a query string, or can lead to internal
sub-processing, external request redirection, or internal proxy
throughput.
Further details, discussion, and examples, are provided in the detailed mod_rewrite documentation.
The off this module does no runtime processing at
all. It does not even update the SCRIPT_URx
environment variables.
Use this directive to disable the module instead of
commenting out all the
Note that rewrite configurations are not
inherited by virtual hosts. This means that you need to have a
RewriteEngine on directive for each virtual host
in which you wish to use rewrite rules.
prg
are not started during server initialization if they're defined in a
context that does not have on
MaxRedirects is no longer available in version 2.1 and
laterThe
inherit.htaccess configuration or
The /') then it is assumed to be relative to the
Server Root. The directive should occur only once per
server config.
/dev/null, because
although the rewriting engine does not then output to a
logfile it still creates the logfile output internally.
This will slow down the server with no advantage
to the administrator! To disable logging either
remove or comment out the RewriteLogLevel 0!
The
To disable the logging of rewriting actions simply set Level to 0. This disables all rewrite action logs.
This directive sets the filename for a synchronization
lockfile which mod_rewrite needs to communicate with
The
The MapName is the name of the map and will be used to specify a mapping-function for the substitution strings of a rewriting rule via one of the following constructs:
${ MapName :
LookupKey }
${ MapName :
LookupKey | DefaultValue
}
When such a construct occurs, the map MapName is consulted and the key LookupKey is looked-up. If the key is found, the map-function construct is substituted by SubstValue. If the key is not found then it is substituted by DefaultValue or by the empty string if no DefaultValue was specified.
For example, you might define a
You would then be able to use this map in a
The following combinations for MapType and MapSource can be used:
txt, MapSource: Unix filesystem
path to valid regular file
This is the standard rewriting map feature where the MapSource is a plain ASCII file containing either blank lines, comment lines (starting with a '#' character) or pairs like the following - one per line.
MatchingKey SubstValue
## ## map.txt -- rewriting map ## Ralf.S.Engelschall rse # Bastard Operator From Hell Mr.Joe.Average joe # Mr. Average
rnd, MapSource: Unix filesystem
path to valid regular file
This is identical to the Standard Plain Text variant
above but with a special post-processing feature: After
looking up a value it is parsed according to contained
``|'' characters which have the meaning of
``or''. In other words they indicate a set of
alternatives from which the actual returned value is
chosen randomly. For example, you might use the following map
file and directives to provide a random load balancing between
several back-end server, via a reverse-proxy. Images are sent
to one of the servers in the 'static' pool, while everything
else is sent to one of the 'dynamic' pool.
Example:
## ## map.txt -- rewriting map ## static www1|www2|www3|www4 dynamic www5|www6
dbm[=type], MapSource: Unix filesystem
path to valid regular file
Here the source is a binary format DBM file containing the same contents as a Plain Text format file, but in a special representation which is optimized for really fast lookups. The type can be sdbm, gdbm, ndbm, or db depending on compile-time settings. If the type is omitted, the compile-time default will be chosen.
To create a dbm file from a source text file, use the httxt2dbm utility.
int, MapSource: Internal Apache
function
Here, the source is an internal Apache function. Currently you cannot create your own, but the following functions already exist:
prg, MapSource: Unix filesystem
path to valid regular file
Here the source is a program, not a map file. To
create it you can use a language of your choice, but
the result has to be an executable program (either
object-code or a script with the magic cookie trick
'#!/path/to/interpreter' as the first
line).
This program is started once, when the Apache server
is started, and then communicates with the rewriting engine
via its stdin and stdout
file-handles. For each map-function lookup it will
receive the key to lookup as a newline-terminated string
on stdin. It then has to give back the
looked-up value as a newline-terminated string on
stdout or the four-character string
``NULL'' if it fails (i.e., there
is no corresponding value for the given key).
External rewriting programs are not started if they're defined in a
context that does not have on
A trivial program which will implement a 1:1 map (i.e., key == value) could be:
#!/usr/bin/perl
$| = 1;
while (<STDIN>) {
# ...put here any transformations or lookups...
print $_;
}
But be very careful:
stdout. Avoid this, as it will cause a deadloop!
``$|=1'' is used above, to prevent this.SQL Query
MapType: dbd or fastdbd,
MapSource: An SQL SELECT statement that takes a single
argument and returns a single value.
This uses fastdbd caches database lookups internally,
dbd doesn't. So dbd incurs a
performance penalty but responds immediately if the database
contents are updated, while fastdbd is more
efficient but won't re-read database contents until server
restart.
If a query returns more than one row, a random row from the result set is used.
The
mtime of the
mapfile changes or the server does a restart. This way you can have
map-functions in rules which are used for every
request. This is no problem, because the external lookup only happens
once!
The .htaccess file,
If your URL path does not exist on the filesystem,
you must use .htaccess file where you want to use
The example below demonstrates how to map
http://example.com/foo/index.html to
/home/www/example/newsite.html, in a .htaccess
file. This assumes that the content available at
http://example.com/ is on disk at
/home/www/example/.
RewriteEngine On RewriteBase /foo/ RewriteRule ^index\.html$ newsite.html
The
TestString can contain plain text, any of the
following expanded constructs, or both.
$N
(1 <= N <= 9). They provide access to the grouped
parts of the current RewriteRule pattern. The grouped
parts of the pattern are those in parentheses.%N
(1 <= N <= 9). They provide access to the grouped
parts of the last-matched RewriteCond pattern. The
grouped parts of the pattern are those in parentheses.${mapname:key|default}.
See the RewriteMap documentation
for more details.
%{ NAME_OF_VARIABLE },
where NAME_OF_VARIABLE is one of the server variables from
the table below:
| HTTP headers: | connection & request: | |
|---|---|---|
|
HTTP_USER_AGENT HTTP_REFERER HTTP_COOKIE HTTP_FORWARDED HTTP_HOST HTTP_PROXY_CONNECTION HTTP_ACCEPT |
REMOTE_ADDR REMOTE_HOST REMOTE_PORT REMOTE_USER REMOTE_IDENT REQUEST_METHOD SCRIPT_FILENAME PATH_INFO QUERY_STRING AUTH_TYPE |
|
| server internals: | date and time: | specials: |
|
DOCUMENT_ROOT SERVER_ADMIN SERVER_NAME SERVER_ADDR SERVER_PORT SERVER_PROTOCOL SERVER_SOFTWARE |
TIME_YEAR TIME_MON TIME_DAY TIME_HOUR TIME_MIN TIME_SEC TIME_WDAY TIME |
API_VERSION THE_REQUEST REQUEST_URI REQUEST_FILENAME IS_SUBREQ HTTPS |
The following variables are specific to
IS_SUBREQAPI_VERSIONTHE_REQUESTGET
/index.html HTTP/1.1"). This does not
include any additional headers sent by the
browser.REQUEST_URIREQUEST_FILENAMEHTTPSNote that the SCRIPT_FILENAME and
REQUEST_FILENAME
variables both contain the value of the
filename field of the internal
request_rec structure.
If a substitution occurs and rewriting continues,
the value of both variables will be updated accordingly.
In a per-server context, before the
request is mapped to the filesystem, these variables contain the value
of REQUEST_URI, because the full filesystem path is not
yet known. To obtain the full filesystem
path of a request in a per-server context, use a URL-based
look-ahead %{LA-U:REQUEST_FILENAME} to determine
the final value of REQUEST_FILENAME.
Other available variables include the following:
%{ENV:variable}, where variable can be
any environment variable.%{SSL:variable}, where variable is the
name of an SSL environment
variable. If %{HTTP:header}, where header can be
any HTTP MIME-header name. For example,
%{HTTP:Proxy-Connection} is the value of the HTTP header
``Proxy-Connection:''. If a HTTP header is used in a
condition, and the condition evaluates to true, then that
header is added to the Vary header of the response. This is used to
ensure proper caching.
If a previous condition has evaluated to true and the
'ornext|OR' flag is in use, later
conditions are not evaluated, and therefore headers are not added to the
Vary header.%{LA-U:variable}, which is used to perform
an internal URL-based sub-request, to determine the final
value of variable. This can be used to access the value of
a variable which is to be set in a later phase. For example, the
REMOTE_USER variable is set in the authorization phase of
processing. This comes after the URL translation phase, where rewrite
rules in httpd.conf are applied, but before the fixup
phase, where rewrite rules in a .htaccess file are applied.
Therefore, to obtain the value of the REMOTE_USER variable
within httpd.conf, you must use %{LA-U:REMOTE_USER}. To obtain the value of the
REMOTE_USER variable within a .htaccess file,
simply use %{REMOTE_USER}CondPattern is the condition pattern, a regular expression which is applied to the current instance of the TestString. TestString is first evaluated, before being matched against CondPattern.
Remember: CondPattern is a perl compatible regular expression with some additions:
!' character (exclamation mark) to specify a
non-matching pattern."" (two quotation marks) this
compares TestString to the empty string.[flags]
as the third argument to the RewriteCond
directive, where flags is a comma-separated list of any of the
following flags:
nocase|NC'
(no case)ornext|OR'
(or next condition)
RewriteCond %{REMOTE_HOST} ^host1.* [OR]
RewriteCond %{REMOTE_HOST} ^host2.* [OR]
RewriteCond %{REMOTE_HOST} ^host3.*
RewriteRule ...some special stuff for any of these hosts...
novary|NV'
(no vary)Example:
To rewrite the Homepage of a site according to the
``User-Agent:'' header of the request, you can
use the following:
RewriteCond %{HTTP_USER_AGENT} ^Mozilla.*
RewriteRule ^/$ /homepage.max.html [L]
RewriteCond %{HTTP_USER_AGENT} ^Lynx.*
RewriteRule ^/$ /homepage.min.html [L]
RewriteRule ^/$ /homepage.std.html [L]
Explanation: If you use a browser which identifies itself as 'Mozilla' (including Netscape Navigator, Mozilla etc), then you get the max homepage (which could include frames, or other special features). If you use the Lynx browser (which is terminal-based), then you get the min homepage (which could be a version designed for easy, text-only browsing). If neither of these conditions apply (you use any other browser, or your browser identifies itself as something non-standard), you get the std (standard) homepage.
The
Pattern is a perl compatible regular expression. On the first RewriteRule it is applied to the (%-encoded) URL-path of the request; subsequent patterns are applied to the output of the last matched RewriteRule.
The Pattern will initially be matched against the part of the URL after the hostname and port, and before the query string.
When the RewriteRule appears in per-directory (htaccess) context, the
Pattern is matched against what remains of the URL after removing
the prefix that lead Apache to the current rules (see the
^/ never
matches in per-directory context.
If you wish to match against the hostname, port, or query string, use a
%{HTTP_HOST}, %{SERVER_PORT}, or
%{QUERY_STRING} variables respectively. If you wish to
match against the full URL-path in a per-directory (htaccess) RewriteRule,
use the %{REQUEST_URI} variable.
For some hints on
In mod_rewrite, the NOT character
('!') is also available as a possible pattern
prefix. This enables you to negate a pattern; to say, for instance:
``if the current URL does NOT match this
pattern''. This can be used for exceptional cases, where
it is easier to match the negative pattern, or as a last
default rule.
$N in the substitution string!
The Substitution of a rewrite rule is the string that replaces the original URL-path that was matched by Pattern. The Substitution may be a:
/www/file.html, then this will be treated as a
URL-path unless a directory named www
exists at the root or your file-system, in which case it will
be treated as a file-system path. If you wish other
URL-mapping directives (such as [PT] flag as
described below.[R] flag below.- (dash)In addition to plain text, the Substition string can include
$N) to the RewriteRule
pattern%N) to the last matched
RewriteCond pattern%{VARNAME})${mapname:key|default})Back-references are identifiers of the form
$N
(N=0..9), which will be replaced
by the contents of the Nth group of the
matched Pattern. The server-variables are the same
as for the TestString of a RewriteCond
directive. The mapping-functions come from the
RewriteMap directive and are explained there.
These three types of variables are expanded in the order above.
As already mentioned, all rewrite rules are
applied to the Substitution (in the order in which
they are defined
in the config file). The URL is completely
replaced by the Substitution and the
rewriting process continues until all rules have been applied,
or it is explicitly terminated by a
L flag.
By default, the query string is passed through unchanged. You
can, however, create URLs in the substitution string containing
a query string part. Simply use a question mark inside the
substitution string to indicate that the following text should
be re-injected into the query string. When you want to erase an
existing query string, end the substitution string with just a
question mark. To combine new and old query strings, use the
[QSA] flag.
Additionally you can set special actions to be performed by
appending [flags]
as the third argument to the RewriteRule
directive. Flags is a comma-separated list, surround by square
brackets, of any of the following flags:
B' (escape backreferences)Apache has to unescape URLs before mapping them, so backreferences will be unescaped at the time they are applied. Using the B flag, non-alphanumeric characters in backreferences will be escaped. For example, consider the rule:
This will map /C++ to
/index.php?show=/C++. But it will also map
/C%2b%2b to /index.php?show=/C++, because
the %2b has been unescaped. With the B flag, it will
instead map to /index.php?show=/C%2b%2b.
This escaping is particularly necessary in a proxy situation, when the backend may break if presented with an unescaped URL.
chain|C'
(chained with next rule).www'' part, inside a per-directory rule set,
when you let an external redirect happen (where the
``.www'' part should not occur!).cookie|CO=NAME:VAL:domain[:lifetime[:path[:secure[:httponly]]]]'
(set cookie)HttpOnly flag is used, making the cookie inaccessible
to JavaScript code on browsers that support this feature.discardpathinfo|DPI'
(discard PATH_INFO)This flag is available from 2.2.12
In per-directory context, the URI each
The current URI can be the initial URI as requested by the client, the result of a previous round of mod_rewrite processing, or the result of a prior rule in the current round of mod_rewrite processing.
In contrast, the PATH_INFO that is appended to the URI before each
rule reflects only the value of PATH_INFO before this round of
mod_rewrite processing. As a consequence, if large portions
of the URI are matched and copied into a substitution in multiple
Use this flag on any substitution where the PATH_INFO that resulted from the previous mapping of this request to the filesystem is not of interest. This flag permanently forgets the PATH_INFO established before this round of mod_rewrite processing began. PATH_INFO will not be recalculated until the current round of mod_rewrite processing completes. Subsequent rules during this round of processing will see only the direct result of substitutions, without any PATH_INFO appended.
env|E=VAR:VAL'
(set environment variable)$N and
%N) which will be expanded. You can use this
flag more than once, to set more than one variable. The
variables can later be dereferenced in many situations, most commonly
from within XSSI (via <!--#echo
var="VAR"-->) or CGI ($ENV{'VAR'}).
You can also dereference the variable in a later RewriteCond pattern, using
%{ENV:VAR}. Use this to strip
information from URLs, while maintaining a record of that information.forbidden|F' (force URL
to be forbidden)gone|G' (force URL to be
gone)handler|H=Content-handler'
(force Content handler)cgi-script''.- (dash) as the substitution, otherwise the request
will fail.last|L'
(last rule)last command or the
break command in C. Use this flag to prevent the
currently rewritten URL from being rewritten further by
following rules. Remember, however, that if the
next|N'
(next round)next command or
the continue command in C. Use
this flag to restart the rewriting process -
to immediately go to the top of the loop.
Be careful not to create an infinite
loop!nocase|NC'
(no case)noescape|NE'
(no URI escaping of
output)/foo/zed' into a safe
request for '/bar?arg=P1=zed'.
nosubreq|NS'
(not for internal
sub-requests)This flag forces the rewriting engine to skip a
rewriting rule if the current request is an internal
sub-request. For instance, sub-requests occur internally
in Apache when index.xxx files). On sub-requests it is not
always useful, and can even cause errors, if
the complete set of rules are applied. Use this flag to
exclude some rules.
To decide whether or not to use this rule: if you prefix URLs with CGI-scripts, to force them to be processed by the CGI-script, it's likely that you will run into problems (or significant overhead) on sub-requests. In these cases, use this flag.
proxy|P' (force
proxy)http://hostname) which can be
handled by the Apache proxy module. If not, you will get an
error from the proxy module. Use this flag to achieve a
more powerful implementation of the ProxyPass directive,
to map remote content into the namespace of the local
server.
Note:
passthrough|PT'
(pass through to next
handler)uri field of the internal
request_rec structure to the value of the
filename field. This flag is just a hack to
enable post-processing of the output of
RewriteRule directives, using
Alias, ScriptAlias,
Redirect, and other directives from
various URI-to-filename translators. For example, to rewrite
/abc to /def using
/def to /ghi using
PT flag,
uri=/abc/... to
filename=/def/... as a full API-compliant
URI-to-filename translator should do. Then
mod_alias will try to do a
URI-to-filename transition, which will fail.
Note: You must use this flag if you want to
mix directives from different modules which allow
URL-to-filename translators. The typical example
is the use of
The PT flag implies the L flag:
rewriting will be stopped in order to pass the request to
the next phase of processing.
qsappend|QSA'
(query string
append)redirect|R
[=code]' (force redirect)Prefix Substitution with
http://thishost[:thisport]/ (which makes the
new URL a URI) to force a external redirection. If no
code is given, a HTTP response of 302 (MOVED
TEMPORARILY) will be returned. If you want to use other
response codes, simply specify the appropriate number or use
one of the following symbolic names: temp
(default), permanent,
seeother. Use this for rules to canonicalize
the URL and return it to the client - to translate
``/~'' into ``/u/'', or to always
append a slash to /u/user, etc.
Note: When you use this flag, make sure
that the substitution field is a valid URL! Otherwise, you
will be redirecting to an invalid location. Remember that
this flag on its own will only prepend
http://thishost[:thisport]/ to the URL, and
rewriting will continue. Usually, you will want to stop
rewriting at this point, and redirect immediately. To stop
rewriting, you should add the 'L' flag.
While this is typically used for redirects, any valid status
code can be given here. If the status code is outside the redirect
range (300-399), then the Substitution string is dropped
and rewriting is stopped as if the L flag was
used.
skip|S=num'
(skip next rule(s))skip=N, where N is the number of rules in the
else-clause. (This is not the same as the
'chain|C' flag!)type|T=MIME-type'
(force MIME type)- (dash)
as the substitution, otherwise the MIME-type set with this flag
is lost due to an internal re-processing. When the substitution string begins with a string
resembling "/~user" (via explicit text or backreferences), mod_rewrite performs
home directory expansion independent of the presence or configuration
of
This expansion does not occur when the PT
flag is used on the
The rewrite engine may be used in .htaccess files. To enable the
rewrite engine for these files you need to set
"RewriteEngine On" and
"Options FollowSymLinks" must be enabled. If your
administrator has disabled override of FollowSymLinks for
a user's directory, then you cannot use the rewrite engine. This
restriction is required for security reasons.
When using the rewrite engine in .htaccess files the
per-directory prefix (which always is the same for a specific
directory) is automatically removed for the pattern matching
and automatically added after the substitution has been
done. This feature is essential for many sorts of rewriting; without
this, you would always have to match the parent directory, which is
not always possible. There is one exception: If a substitution string
starts with http://, then the directory prefix will
not be added, and an external redirect (or proxy
throughput, if using flag P) is forced. See the
The rewrite engine may also be used in .htaccess
files. It is usually simpler, however, to avoid the prefix substitution
complication by putting the rewrite rules in the main server or
virtual host context, rather than in a
Although rewrite rules are syntactically permitted in
Here are all possible substitution combinations and their meanings:
Inside per-server configuration
(httpd.conf)
for request ``GET
/somepath/pathinfo'':
Given Rule Resulting Substitution
---------------------------------------------- ----------------------------------
^/somepath(.*) otherpath$1 invalid, not supported
^/somepath(.*) otherpath$1 [R] invalid, not supported
^/somepath(.*) otherpath$1 [P] invalid, not supported
---------------------------------------------- ----------------------------------
^/somepath(.*) /otherpath$1 /otherpath/pathinfo
^/somepath(.*) /otherpath$1 [R] http://thishost/otherpath/pathinfo
via external redirection
^/somepath(.*) /otherpath$1 [P] doesn't make sense, not supported
---------------------------------------------- ----------------------------------
^/somepath(.*) http://thishost/otherpath$1 /otherpath/pathinfo
^/somepath(.*) http://thishost/otherpath$1 [R] http://thishost/otherpath/pathinfo
via external redirection
^/somepath(.*) http://thishost/otherpath$1 [P] doesn't make sense, not supported
---------------------------------------------- ----------------------------------
^/somepath(.*) http://otherhost/otherpath$1 http://otherhost/otherpath/pathinfo
via external redirection
^/somepath(.*) http://otherhost/otherpath$1 [R] http://otherhost/otherpath/pathinfo
via external redirection
(the [R] flag is redundant)
^/somepath(.*) http://otherhost/otherpath$1 [P] http://otherhost/otherpath/pathinfo
via internal proxy
Inside per-directory configuration for
/somepath
(/physical/path/to/somepath/.htacccess, with
RewriteBase /somepath)
for request ``GET
/somepath/localpath/pathinfo'':
Given Rule Resulting Substitution
---------------------------------------------- ----------------------------------
^localpath(.*) otherpath$1 /somepath/otherpath/pathinfo
^localpath(.*) otherpath$1 [R] http://thishost/somepath/otherpath/pathinfo
via external redirection
^localpath(.*) otherpath$1 [P] doesn't make sense, not supported
---------------------------------------------- ----------------------------------
^localpath(.*) /otherpath$1 /otherpath/pathinfo
^localpath(.*) /otherpath$1 [R] http://thishost/otherpath/pathinfo
via external redirection
^localpath(.*) /otherpath$1 [P] doesn't make sense, not supported
---------------------------------------------- ----------------------------------
^localpath(.*) http://thishost/otherpath$1 /otherpath/pathinfo
^localpath(.*) http://thishost/otherpath$1 [R] http://thishost/otherpath/pathinfo
via external redirection
^localpath(.*) http://thishost/otherpath$1 [P] doesn't make sense, not supported
---------------------------------------------- ----------------------------------
^localpath(.*) http://otherhost/otherpath$1 http://otherhost/otherpath/pathinfo
via external redirection
^localpath(.*) http://otherhost/otherpath$1 [R] http://otherhost/otherpath/pathinfo
via external redirection
(the [R] flag is redundant)
^localpath(.*) http://otherhost/otherpath$1 [P] http://otherhost/otherpath/pathinfo
via internal proxy