GCS Amplitude
GCS Amplitude

Apache Module mod_rewrite

module uses a rule-based rewriting engine, based on a PCRE regular-expression parser, to rewrite requested URLs on the fly. By default, mod_rewrite

maps a URL to a filesystem path. However, it can also be used to redirect one URL to another URL, or to invoke an internal proxy fetch.mod_rewrite

provides a flexible and powerful way to manipulate URLs using an unlimited number of rules. Each rule can have an unlimited number of attached rule conditions, to allow you to rewrite URL based on server variables, environment variables, HTTP headers, or time stamps.mod_rewrite

operates on the full URL path, including the path-info section. A rewrite rule can be invoked in mod_rewriteapache2.conf

. 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.

will slow down your Apache HTTP Server dramatically! Use a log level higher than trace2

only for debugging! LogLevel alert rewrite:trace3

Those familiar with earlier versions of

will no doubt be looking for the mod_rewriteRewriteLog

directives. This functionality has been completely replaced by the new per-module logging configuration mentioned above.

To get just the

-specific log messages, pipe the log file through grep:mod_rewrite

tail -f error_log|fgrep '[rewrite:'

This directive is required when you use a relative path in a substitution in per-directory (htaccess) context unless either of the following conditions are true:

(as opposed to reachable by other means, such as Alias

, suffixed by the relative substitution is also valid as a URL path on the server (this is rare). In the example below, RewriteBase

is necessary to avoid rewriting to http://example.com/opt/myapp-1.2.3/welcome.html since the resource was not relative to the document root. This misconfiguration would normally cause the server to look for an "opt" directory under the document root.

TestString is a string which can contain the following expanded constructs in addition to plain text:

conditions. $0 provides access to the whole string matched by that pattern. %N

| HTTP headers: | connection & request: | | |---|---|---| | HTTPACCEPT HTTPCOOKIE HTTPFORWARDED HTTPHOST HTTPPROXYCONNECTION HTTPREFERER HTTPUSERAGENT | AUTHTYPE CONNREMOTEADDR CONTEXTPREFIX CONTEXTDOCUMENTROOT IPV6 PATHINFO QUERYSTRING REMOTEADDR REMOTEHOST REMOTEIDENT REMOTEPORT REMOTEUSER REQUESTMETHOD SCRIPTFILENAME | | | server internals: | date and time: | specials: | | DOCUMENTROOT SCRIPTGROUP SCRIPTUSER SERVERADDR SERVERADMIN SERVERNAME SERVERPORT SERVERPROTOCOL SERVERSOFTWARE | TIMEYEAR TIMEMON TIMEDAY TIMEHOUR TIMEMIN TIMESEC TIMEWDAY TIME | APIVERSION CONNREMOTEADDR HTTPS ISSUBREQ REMOTEADDR REQUESTFILENAME REQUESTSCHEME REQUESTURI THE_REQUEST |

These variables all correspond to the similarly named HTTP MIME-headers, C variables of the Apache HTTP Server or struct tm

fields of the Unix system. Most are documented here or elsewhere in the Manual or in the CGI specification.

SERVERNAME and SERVERPORT depend on the values of

is referenced. Otherwise, such as when used in virtual host context, the same value as REQUEST_URI

. Depending on the value of AcceptPathInfo

, the server may have only used some leading components of the REQUEST_URI

"). This does not include any additional headers sent by the browser. This value has not been unescaped (decoded), unlike most other variables below.If the TestString has the special value expr

, the CondPattern will be treated as an ap_expr. HTTP headers referenced in the expression will be added to the Vary header if the novary

flag is not given.

Other things you should be aware of:

field of the internal request_rec

structure of the Apache HTTP Server. The first name is the commonly known CGI variable name while the second is the appropriate counterpart of REQUEST_URI (which contains the value of the uri

If a substitution occurred and the rewriting continues, the value of both variables will be updated accordingly.

If used in per-server context (i.e., before the request is mapped to the filesystem) SCRIPTFILENAME and REQUESTFILENAME cannot contain the full local filesystem path since the path is unknown at this stage of processing. Both variables will initially contain the value of REQUESTURI in that case. In order to obtain the full local filesystem path of the request in per-server context, use an URL-based look-ahead %{LA-U:REQUESTFILENAME}

to determine the final value of REQUEST_FILENAME.

from the Apache httpd server process.%{SSL:variable}

is loaded, but will always expand to the empty string if it is not. Example: %{SSL:SSLCIPHERUSEKEYSIZE}

''. If a HTTP header is used in a condition this header is added to the Vary header of the response in case the condition evaluates to true for the request. It is not added if the condition evaluates to false for the request. Adding the HTTP header to the Vary header of the response is needed for proper caching.

It has to be kept in mind that conditions follow a short circuit logic in the case of the ' ornext|OR' flag so that certain conditions might not be evaluated at all.

For instance, to rewrite according to the REMOTE_USER

variable from within the per-server context (apache2.conf

- this variable is set by the authorization phases, which come after the URL translation phase (during which mod_rewrite operates).

On the other hand, because mod_rewrite implements its per-directory context (.htaccess

can be used to perform an internal (filename-based) sub-request, to determine the final value of 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.

CondPattern is usually a perl compatible regular expression, but there is additional syntax available to perform other useful tests against the Teststring:

' character (exclamation mark) to negate the result of the condition, no matter what kind of ""

(two quotation marks) this compares '-U' (is existing URL, via subrequest)

Checks whether or not TestString is a valid URL, accessible via all the server's currently-configured access controls for that path. This uses an internal subrequest to do the check, so use it with care - it can impact your server's performance!

This flag only returns information about things like access control, authentication, and authorization. This flag does not return information about the status code the configured handler (static file, CGI, proxy, etc.) would have returned.

is used to compare the REFERER

against the site hostname, to block unwanted hotlinking.

directive, where nocase|NC

RewriteCond %{REMOTEHOST} ^host1 [OR] RewriteCond %{REMOTEHOST} ^host2 [OR] RewriteCond %{REMOTE_HOST} ^host3 RewriteRule ...some special stuff for any of these hosts...Without this flag you would have to write the condition/rule pair three times.

To rewrite the Homepage of a site according to the User-Agent:

RewriteCond %{HTTPUSERAGENT} (iPhone|Blackberry|Android) RewriteRule ^/$ /homepage.mobile.html [L] RewriteRule ^/$ /homepage.std.html [L]

Explanation: If you use a browser which identifies itself as a mobile browser (note that the example is incomplete, as there are many other mobile platforms), the mobile version of the homepage is served. Otherwise, the standard page is served.

Use this directive to disable rules in a particular context, rather than commenting out all the

Note that rewrite configurations are not inherited by virtual hosts. This means that you need to have a RewriteEngine on

directives of the type prg

are not started during server initialization if they're defined in a context that does not have RewriteEngine

RewriteMap MapName MapType:MapSource

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:

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. Empty values behave as if the key was absent, therefore it is not possible to distinguish between empty-valued keys and absent keys.

RewriteMap examplemap txt:/path/to/file/map.txt

: toupper, tolower, escape or unescape. (Further details, and numerous examples, may be found in the RewriteMap HowTo

is no longer available in version 2.1 and laterThe RewriteOptions

This forces the current configuration to inherit the configuration of the parent. In per-virtual-server context, this means that the maps, conditions and rules of the main server are inherited. In per-directory context this means that conditions and rules of the parent directory's .htaccess

sections are inherited. The inherited rules are virtually copied to the section where this directive is being used. If used in combination with local rules, the inherited rules are copied behind the local rules. The position of this directive - below or above of local rules - has no influence on this behavior. If local rules forced the rewriting to stop, the inherited rules won't be processed.

above, but the rules from the parent scope are applied before rules specified in the child scope.

If this option is enabled, all child configurations will inherit the configuration of the current configuration. It is equivalent to specifying RewriteOptions Inherit

option for more details on how the parent-child relationships are handled.

This option forces the current and child configurations to ignore all rules that would be inherited from a parent specifying InheritDown

will ignore URLs that map to a directory on disk but lack a trailing slash, in the expectation that the mod_rewrite

module will issue the client with a redirect to the canonical URL with a trailing slash.mod_dir

option can be enabled to ensure that rewrite rules are no longer ignored. This option makes it possible to apply rewrite rules within .htaccess files that match the directory without a trailing slash, if so desired.

will only process the rewrite rules if the request URI is a mod_rewriteURL-path. This avoids some security issues where particular rules could allow "surprising" pattern expansions (see CVE-2011-3368 and CVE-2011-4317). To lift the restriction on matching a URL-path, the AllowAnyURI

will apply the rule set to any request URI string, regardless of whether that string matches the URL-path grammar required by the HTTP specification.mod_rewrite

Enabling this option will make the server vulnerable to security issues if used with rewrite rules which are not carefully authored. It is strongly recommended that this option is not used. In particular, beware of input strings containing the '@

' character which could change the interpretation of the transformed URI, as per the above CVE names.

is copied from where it's explicitly defined into any sub-directory or sub-location that doesn't define its own RewriteBase

. This was the default behavior in 2.4.0 through 2.4.3, and the flag to restore it is available Apache HTTP Server 2.4.4 and later.RewriteBase

context, The VirtualHostPattern will initially be matched against the part of the URL after the hostname and port, and before the query string (e.g. "/app1/index.html").

and htaccess context, the DirectoryPattern will initially be matched against the filesystem path, after removing the prefix that led the server to the current RewriteRule

" must be enabled. If your administrator has disabled override of FollowSymLinks

directive for more information regarding what prefix will be added back to relative substitutions.%{REQUEST_URI}

sections, this should never be necessary and is unsupported.For some hints on regular expressions, see the mod_rewrite Introduction.

') 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.

in the substitution string! The [ Substitution] of a rewrite rule is the string that replaces the original URL-path that was matched by

tries to guess whether you have specified a file-system path or a URL-path by checking to see if the first segment of the path exists at the root of the file-system. For example, if you specify a /www/file.html

checks to see whether the hostname matches the current host. If it does, the scheme and hostname are stripped out and the resulting path is treated as a URL-path. Otherwise, an external redirect is performed for the given URL. To force an external redirect back to the current host, see the [R]

)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

Rewrite rules are applied to the results of previous rewrite rules, in the order in which they are defined in the config file. The URL-path or file-system path (see "What is matched?", above) is completely replaced by the Substitution and the rewriting process continues until all rules have been applied, or it is explicitly terminated by an , or other flag which implies immediate termination, such as

.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]

Additionally you can set special [actions] to be performed by appending [ flags] as the third argument to the

directive. | Flag and syntax | Function | |---|---| | B | Escape non-alphanumeric characters before applying the transformation. | | chain|C | Rule is chained to the following rule. If the rule fails, the rule(s) chained to it will be skipped. | cookie|CO=NAME:VAL | Sets a cookie in the client browser. Full syntax is: CO=NAME:VAL:domain[:lifetime[:path[:secure[:httponly]]]] | | discardpath|DPI | Causes the PATHINFO portion of the rewritten URI to be discarded. | | END | Stop the rewriting process immediately and don't apply any more rules. Also prevents further execution of rewrite rules in per-directory and .htaccess context. (Available in 2.3.9 and later) | env|E=[!]VAR[:VAL] | Causes an environment variable VAR to be set (to the value VAL if provided). The form !VAR causes the environment variable VAR to be unset. | | forbidden|F | Returns a 403 FORBIDDEN response to the client browser. | | gone|G | Returns a 410 GONE response to the client browser. | Handler|H=Content-handler | Causes the resulting URI to be sent to the specified Content-handler for processing. | | last|L | Stop the rewriting process immediately and don't apply any more rules. Especially note caveats for per-directory and .htaccess context (see also the END flag). | | next|N | Re-run the rewriting process, starting again with the first rule, using the result of the ruleset so far as a starting point. | | nocase|NC | Makes the pattern comparison case-insensitive. | | noescape|NE | Prevent modrewrite from applying hexcode escaping of special characters in the result of the rewrite. | | nosubreq|NS | Causes a rule to be skipped if the current request is an internal sub-request. | | proxy|P | Force the substitution URL to be internally sent as a proxy request. | | passthrough|PT | Forces the resulting URI to be passed back to the URL mapping engine for processing of other URI-to-filename translators, such as Alias or Redirect . | | qsappend|QSA | Appends any query string from the original request URL to any query string created in the rewrite target. | | qsdiscard|QSD | Discard any query string attached to the incoming URI. | redirect|R[=code] | Forces an external redirect, optionally with the specified HTTP status code. | skip|S=num | Tells the rewriting engine to skip the next num rules if the current rule matches. | type|T=MIME-type | Force the |

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

Here are all possible substitution combinations and their meanings:

| 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 |

| 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 |

Modules | Directives | FAQ | Glossary | Sitemap

Apache HTTP Server Version 2.4

Apache Module mod_rewrite

Available Languages: en | fr

Logging

mod_rewrite offers detailed logging of its actions at the trace1 to trace8 log levels. The log level can be set specifically for mod_rewrite using the LogLevel directive: Up to level debug, no actions are logged, while trace8 means that practically all actions are logged.

RewriteBase Directive

The RewriteBase directive specifies the URL prefix to be used for per-directory (htaccess) RewriteRule directives that substitute a relative path.

RewriteCond Directive

The RewriteCond directive defines a rule condition. One or more RewriteCond can precede a RewriteRule directive. The following rule is then only used if both the current state of the URI matches its pattern, and if these conditions are met.

RewriteEngine Directive

The RewriteEngine directive enables or disables the runtime rewriting engine. If it is set to off this module does no runtime processing at all. It does not even update the SCRIPT_URx environment variables.

RewriteMap Directive

The RewriteMap directive defines a Rewriting Map which can be used inside rule substitution strings by the mapping-functions to insert/substitute fields through a key lookup. The source of this lookup can be of various types.

RewriteOptions Directive

The RewriteOptions directive sets some special options for the current per-server or per-directory configuration. The Option string can currently only be one of the following:

RewriteRule Directive

The RewriteRule directive is the real rewriting workhorse. The directive can occur more than once, with each instance defining a single rewrite rule. The order in which these rules are defined is important - this is the order in which they will be applied at run-time.