Module mod_rewrite
Module mod_rewrite supports directives for the IBM® HTTP Server for i Web server.
Summary
This module allows you to control URL access to your HTTP Server.
For example, to prevent a particular user agent called Web crawler from accessing any pages on the server. To do this, include the following directives in your configuration:
RewriteEngine on RewriteCond %{HTTP_USER_AGENT} ^Webcrawler RewriteRule ^.*$ - [F,L]
The first line enables the rewrite engine. The second line provides a test that returns true if the HTTP_USER_AGENT string starts with the letters Web crawler. If the second line is true, then the third line takes any URL string and returns a forbidden message to the client.
Directives
RewriteBase
Module: mod_rewrite | |
Syntax: RewriteBase Base_URL | |
Default: RewriteBase physical directory path | |
Context: Directory, but not Location, .htaccess | |
Override: FileInfo | |
Origin: Apache | |
Example: RewriteBase /xyz |
The RewriteBase directive explicitly sets the base URL for per-directory rewrites. As you will see below, RewriteRule can be used in per-directory config files (.htaccess). There it will act locally (for example, the local directory prefix is stripped at this stage of processing and your rewriting rules act only on the remainder). At the end it is automatically added back to the path.
When a substitution occurs for a new URL, this module has to re-inject the URL into the processing server. To be able to do this it needs to know what the corresponding URL-prefix or URL-base is. By default this prefix is the corresponding filepath itself. At most, Web sites URLs are not directly related to physical filename paths, so this assumption is usually incorrect. In this case, you have to use the RewriteBase directive to specify the correct URL-prefix.
Assume the following per-directory configuration file (/abc/def is the physical path of /xyz, and the server has the 'Alias /xyz /ABC/def' established).
RewriteEngine On
RewriteBase /xyz
RewriteRule ^old\.html$ new.html
In the above example, a request to /xyz/old.html is correctly rewritten to the physical file /ABC/def/new.html.
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.
DocumentRoot /var/www/example.com
AliasMatch /myapp /opt/myapp-1.2.3
<Directory /opt/myapp-1.2.3>
RewriteEngine On
RewriteBase /myapp/
RewriteRule ^index\.html$ welcome.html
</Directory>
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:
- The original request, and the substitution, are underneath the DocumentRoot (as opposed to reachable by other means, such as Alias).
- The filesystem path to the directory containing the RewriteRule, suffixed by the relative substitution is also valid as a URL path on the server (this is rare).
- This directive may be omitted when the request is mapped via Alias or mod_userdir.
RewriteCond
Module: mod_rewrite | |
Syntax: RewriteCond TestString CondPattern [flags] | |
Default: none | |
Context: server config, virtual host, directory, .htaccess | |
Override: FileInfo | |
Origin: Apache | |
Example: RewriteCond %{HTTP_USER_AGENT} ^Mozilla.* |
The RewriteCond directive defines a rule condition. Precede a RewriteRule directive with one or more RewriteCond directives. The following rewriting rule is only used if its pattern matches the current state of the URI and if these additional conditions apply.
- Parameter One: TestString
- The TestString parameter can contain the following expanded
constructs in addition to plain text:
- RewriteRule backreferences: These are backreferences of
the form.
- $N
- (0 <= N <= 9) that provide access to the grouped sections (those in parenthesis) of the pattern from the corresponding RewriteRule directive (the one following the current RewriteCond directives).
- RewriteCond backreferences: These are backreferences of
the form.
- %N
- (0 <= N <= 9) that provide access to the grouped sections (those in parenthesis) of the pattern from the last matched RewriteCond directive in the current conditions
- RewriteMap expansions: These are expansions of the form.
- ${mapname:key|default}
- See RewriteMap for more details.
- Server-Variables: These are variables of the form
- %{ NAME_OF_VARIABLE }
- Where NAME_OF_VARIABLE can be a string taken from the following
list:
- HTTP headers
- HTTP_USER_AGENT
- HTTP_REFERRER
- HTTP_COOKIE
- HTTP_FORWARDED
- HTTP_HOST
- HTTP_PROXY_CONNECTION
- HTTP_ACCEPT
- Connection and Request
- AUTH_TYPE
- CONN_REMOTE_ADDR
- CONTEXT_PREFIX
- CONTEXT_DOCUMENT_ROOT
- IPV6
- PATH_INFO
- QUERY_STRING
- REMOTE_ADDR
- REMOTE_HOST
- REMOTE_USER
- REMOTE_IDENT
- REQUEST_METHOD
- SCRIPT_FILENAME
- Server Internals
- DOCUMENT_ROOT
- SERVER_ADMIN
- SERVER_NAME
- SERVER_ADDR
- SERVER_PORT
- SERVER_PROTOCOL
- SERVER_SOFTWARE
- System
- TIME_YEAR
- TIME_MON
- TIME_DAY
- TIME_HOUR
- TIME_MIN
- TIME_SEC
- TIME_WDAY
- TIME
- Special
- API_VERSION
- CONN_REMOTE_ADDR
- HTTPS
- IS_SUBREQ
- REMOTE_ADDR
- REQUEST_URI
- REQUEST_FILENAME
- REQUEST_SCHEME
- THE_REQUEST
Tip:- The variables SCRIPT_FILENAME and REQUEST_FILENAME contain the same value (the value of the filename field of the internal request_rec structure of the server). The first name is just the commonly known CGI variable name while the second is the consistent counterpart to REQUEST_URI (which contains the value of the URI field of request_rec).
- There is the special format: %{ENV:variable} where variable can be any environment variable. This is looked-up via internal structures and (if not found there) via getenv() from the server process.
- There is the special format: %{SSL:variable}, where variable is the name of an SSL environment variable, can be used whether or not mod_ibm_ssl is loaded, but will always expand to the empty string if it is not.
- There is the special format: %{HTTP: header} where header can be any HTTP MIME-header name. This is looked-up from the HTTP request. Example: %{HTTP:Proxy-Connection} is the value of the HTTP header ``Proxy-Connection:''.
- There is the special format %{LA-U:variable} for look-aheads that perform an internal (URL-based) sub-request to determine the final value of variable. Use this when you want to use a variable for rewriting (which is actually set later in an API phase and thus is not available at the current stage). For instance when you want to rewrite according to the REMOTE_USER variable from within the per-server context (httpd.conf file) you have to use %{LA-U:REMOTE_USER} because this variable is set by the authorization phases that come after the URL translation phase where mod_rewrite operates. On the other hand, because mod_rewrite implements its per-directory context (.htaccess file) via the Fixup phase of the API and because the authorization phases come before this phase, you just can use %{REMOTE_USER} there.
- There is the special format: %{LA-F:variable} that performs an internal (filename-based) sub-request to determine the final value of variable. Most of the time this is the same as LA-U above.
- RewriteRule backreferences: These are backreferences of
the form.
- The TestString parameter can contain the following expanded
constructs in addition to plain text:
- Parameter Two: CondPattern
- The CondPattern parameter is the condition pattern (a regular
expression) that is applied to the current instance of the TestString.
TestString is evaluated and then matched against CondPattern.
CondPattern is a standard Extended Regular Expression with some additions:
- You can prefix the pattern string with a '!' character (exclamation mark) to negate the result of the condition, no matter what kind of CondPattern is used.
- You can perform lexicographical string comparisons:
- <CondPattern
- Treats the CondPattern as a plain string and compares it lexically to TestString. True if TestString is lexically lower than CondPattern.
- >CondPattern
- Treats the CondPattern as a plain string and compares it lexically to TestString. True if TestString is lexically greater than CondPattern.
- =CondPattern
- Treats the CondPattern as a plain string and compares it lexically to TestString. True if TestString is lexically equal to CondPattern (the two strings are exactly equal, character by character). If CondPattern is just "" (two quotation marks) this compares TestString to the empty string.
- <=CondPattern
- Treats the CondPattern as a plain string and compares it lexicographically to TestString. True if TestString lexicographically precedes CondPattern, or is equal to CondPattern (the two strings are equal, character for character).
- >=CondPattern
- Treats the CondPattern as a plain string and compares it lexicographically to TestString. True if TestString lexicographically follows CondPattern, or is equal to CondPattern (the two strings are equal, character for character).
- You can perform integer comparisons:
- -eq (is numerically equal to)
- The TestString is treated as an integer, and is numerically compared to the CondPattern. True if the two are numerically equal.
- -ge (is numerically greater than or equal to)
- The TestString is treated as an integer, and is numerically compared to the CondPattern. True if the TestString is numerically greater than or equal to the CondPattern.
- -gt (is numerically greater than)
- The TestString is treated as an integer, and is numerically compared to the CondPattern. True if the TestString is numerically greater than the CondPattern.
- -le (is numerically less than or equal to)
- The TestString is treated as an integer, and is numerically compared to the CondPattern. True if the TestString is numerically less than or equal to the CondPattern. Avoid confusion with the -l by using the -L or -h variant.
- -lt (is numerically less than)
- The TestString is treated as an integer, and is numerically compared to the CondPattern. True if the TestString is numerically less than the CondPattern. Avoid confusion with the -l by using the -L or -h variant.
- You can perform various file attribute tests:
- -d
- Treats the TestString as a pathname and tests if it exists and is a directory.
- -f
- Treats the TestString as a pathname and tests if it exists and is a regular file.
- -F
- Checks whether or not TestString is a valid file, 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!
- -H(is symbolic link, bash convention)
- See -l.
- -l
- Treats the TestString as a pathname and tests if it exists and is a symbolic link.
- -L(is symbolic link, bash convention)
- See -l.
- -s
- Treats the TestString as a pathname and tests if it exists and is a regular file with size greater than zero.
- -U
- Checks if TestString is a valid URL and 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!
- -x
- Treats the TestString as a pathname and tests whether or not it exists, and has executable permissions. These permissions are determined according to the underlying OS.
- If the TestString has the special value expr, the CondPattern will
be treated as an ap_expr.
In the below example, -strmatch is used to compare the REFERER against the site hostname, to block unwanted hotlinking.
RewriteCond expr "! %{HTTP_REFERER} -strmatch '*://%{HTTP_HOST}/*'"
RewriteRule ^/images - [F]
- The CondPattern parameter is the condition pattern (a regular
expression) that is applied to the current instance of the TestString.
TestString is evaluated and then matched against CondPattern.
- Parameter Three: flags
- The flags parameter is appended to the CondPattern parameter.
The flags parameter is a comma -serapertaed list of the following
flags:
- nocase|NC
- This makes the test case-insensitive (there is no difference between 'A-Z' and AZ both in the expanded TestString and the CondPattern). This flag is effective only for comparisons between TestString and CondPattern. It has no effect on filesystem and subrequest checks.
- ornext|OR
- Use this to combine rule conditions with a local OR instead of
the implicit AND. Typical example:
Without this flag you would have to write the cond/rule three times.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
- If a HTTP header is used in the condition, this flag prevents this header from being added to the Vary header of the response. Using this flag might break proper caching of the response if the representation of this response varies on the value of this header. So this flag should be only used if the meaning of the Vary header is well understood.
- The flags parameter is appended to the CondPattern parameter.
The flags parameter is a comma -serapertaed list of the following
flags:
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} (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.
RewriteEngine
Module: mod_rewrite | |
Syntax: RewriteEngine on | off | |
Default: RewriteEngine off | |
Context: server config, virtual host, directory, .htaccess | |
Override: FileInfo | |
Origin: Apache | |
Example: RewriteEngine on |
The RewriteEngine directive enables or disables the runtime rewriting engine. You can use this directive to disable rules in a particular context, rather than commenting out all the RewriteRule directives.
- Parameter: on | off
- If set to on runtime processing is enabled. If it is set to off runtime processing is disabled and this module does not runtime processing at all.
- If it is set to off runtime processing is disabled and this module does no runtime processing at all. It does not even update the SCRIPT_URx environment variables.
RewriteMap
Module: mod_rewrite | |
Syntax: RewriteMap MapName MapType:MapSource | |
Default: none | |
Context: server config, virtual host | |
Override: none | |
Origin: Apache | |
Example: RewriteMap servers rnd:/path/to/file/map.txt |
The RewriteMap directive defines a Rewriting Map that can be used inside rule substitution strings by the mapping-functions to insert or substitute fields through a key lookup. The source of this lookup can be of various types.
- Parameter: MapName
- The MapName parameter is the name of the map and is 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. The following combinations for MapType and MapSource can be used:
- Standard Plain Text
- MapType: txt, MapSource: Path to a file
This is the standard rewriting map feature where the MapSource is a plain text file containing either blank lines, comment lines (starting with a '#' character) or pairs like the following (one per line): MatchingKey SubstituionValue.
File example:
## ## map.txt -- rewriting map ## Ralf.B.Jones rbj # Operator Mr.Joe.Average joe # Mr. Average
Directive example:
RewriteMap real-to-user txt:/path/to/file/map.txt
- Randomized Plain Text
- MapType: rnd, MapSource: Path to a 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 the contained horizontal bar ( | ) characters which mean "or". In other words, the horizontal bars indicate a set of alternatives from which the actual returned value is randomly chosen. This feature was designed for load balancing in a reverse proxy situation where the looked up values are server names.
File example:
## ## map.txt -- rewriting map ## static www1|www2|www3|www4 dynamic www5|www6
Directive example:
RewriteMap servers rnd:/path/to/file/map.txt
- Internal Function
- MapType: int, MapSource: Internal Apache function
The following internal functions are valid:
- toupper
- Converts the looked up key to all upper case.
- tolower
- Converts the looked up key to all lower case.
- escape
- Translates special characters in the looked up key to hex-encodings.
- unescape
- Translates hex-encodings in the looked up key back to special characters.
- The MapName parameter is the name of the map and is used
to specify a mapping-function for the substitution strings of a rewriting
rule via one of the following constructs:
The RewriteMap directive can occur more than once. For each mapping function use one RewriteMap directive to declare its rewriting mapfile. While you cannot declare a map in a per-directory context, it is possible to use this map in a per-directory context.
RewriteOptions
Module: mod_rewrite | |
Syntax: RewriteOptions Option | |
Default: none | |
Context: server config, virtual host, directory, .htaccess | |
Override: FileInfo | |
Origin: Apache | |
Example: RewriteOptions inherit |
The RewriteOptions directive sets some special options for the current per-server or per-directory configuration.
- Parameter: Option
- The Option parameter strings can be one of the following:
Note: Rules inherited from the parent scope are applied after rules specified in the child scope.
RewriteRule
Module: mod_rewrite | |
Syntax: RewriteRule pattern substitution [flags] | |
Default: none | |
Context: server config, virtual host, directory, .htaccess | |
Override: FileInfo | |
Origin: Apache | |
Example: RewriteRule ^/ABC(.*) /def$1 [PT] |
The RewriteRule directive is the real rewriting workhorse. The directive can occur more than once. Each directive then defines one single rewriting rule. The definition order of these rules is important, because this order is used when applying the rules at run-time.
- Parameter One: pattern
- The pattern parameter can be a perl compatible regular expression. On the first RewriteRule, it is matched against the (%-decoded) URL-path (or file-path, depending on the context) of the request. Subsequent patterns are matched against the output of the last matching RewriteRule.
- In VirtualHost context, The Pattern 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").
- In Directory and .htaccess context, the Pattern will initially be matched against the filesystem path, after removing the prefix that led the server to the current RewriteRule (e.g. "app1/index.html" or "index.html" depending on where the directives are defined).
- If you want to match against the hostname, port, or query string, use a RewriteCond with the %{HTTP_HOST}, %{SERVER_PORT}, or %{QUERY_STRING} variables respectively.
- Per-directory Rewrites
- The rewrite engine may be used in .htaccess files and in <Directory> sections, with some additional complexity.
- To enable the rewrite engine in this context, 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 RewriteRule pattern matching and automatically added after any relative (not starting with a slash or protocol name) substitution encounters the end of a rule set. See the RewriteBase directive for more information regarding what prefix will be added back to relative substitutions.
- If you want to match against the full URL-path in a per-directory (htaccess) RewriteRule, use the %{REQUEST_URI} variable in a RewriteCond.
- The removed prefix always ends with a slash, meaning the matching occurs against a string which never has a leading slash. Therefore, a Pattern with ^/ never matches in per-directory context.
- Although rewrite rules are syntactically permitted in <Location> and <Files> sections (including their regular expression counterparts), this should never be necessary and is unsupported. A likely feature to break in these contexts is relative substitutions.
- Additionally in mod_rewrite the NOT character ('!') is a possible pattern prefix. This gives you the ability 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.
- Parameter Two: substitution
- The substitution parameter is the string which is substituted
for (or replaces) the original URL-path for which Pattern matched.
The Substitution may be a:
- file-system path
Designates the location on the file-system of the resource to be delivered to the client. Substitutions are only treated as a file-system path when the rule is configured in server (virtualhost) context and the first component of the path in the substitution exists in the file-system
- URL-path
A DocumentRoot-relative path to the resource to be served. Note that mod_rewrite 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 Substitution string of /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 (or, in the case of using rewrites in a .htaccess file, relative to your document root), in which case it will be treated as a file-system path. If you want other URL-mapping directives (such as Alias) to be applied to the resulting URL-path, use the [PT] flag as described below.
- Absolute URL
If an absolute URL is specified, mod_rewrite 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] flag below.
- - (dash)
A dash indicates that no substitution should be performed (the existing path is passed through untouched). This is used when a flag needs to be applied without changing the path, for example, in conjunction with the C (chain) flag to be able to have more than one pattern to be applied before a substitution occurs.
- file-system path
- Beside plain text you can use back-references $N to the RewriteRule pattern, back-references %N to the last matched RewriteCond pattern, server-variables as in rule condition test-strings (%{VARNAME}) and mapping-function calls (${mapname:key|default}).
- Back-references are $N (N=0..9) identifiers 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 of the above list.
- All the rewriting rules are applied to the results of previous rewrite rules, in the order of definition in the config file). The URL-path or file-system path is completely replaced by the Substitution and the rewriting process goes on until all rules have been applied, or it is explicitly terminated by an L flag, or other flag which implies immediate termination, such as END or F.
- The substitution parameter is the string which is substituted
for (or replaces) the original URL-path for which Pattern matched.
The Substitution may be a:
- Parameter Three: flags
- The flags parameter can additionally be set to special [flags] for Substitution by appending
[flags] as the third argument to the RewriteRule directive. Flags is a comma separated list,
surround by square brackets, of the following flags:
- redirect|R [=code]
- Prefix Substitution with http://thishost[:thisport]/ (which makes the new URL a URI) to force a
external redirection. If no code is given an HTTP response of 302 (MOVED TEMPORARILY) is used. If
you want to use other response codes in the range 300-400 just specify them as a number or use one
of the following symbolic names: temp (default), permanent, seeother. Use it for rules which should
canonicalize the URL and give it back to the client, for example, translate ``/~'' into ``/u/'' or
always append a slash to /u/user, etc. Note: When you use this flag, make sure that the substitution field is a valid URL. If not, you are redirecting to an invalid location! And remember that this flag itself only prefixes the URL with http://thishost[:thisport]/, rewriting continues. Usually you also want to stop and do the redirection immediately. To stop the rewriting you also have to provide the 'L' flag.
- forbidden|F
- This forces the current URL to be forbidden, for example, it immediately sends back an HTTP response of 403 (FORBIDDEN). Use this flag in conjunction with appropriate RewriteConds to conditionally block some URLs.
- gone|G
- This forces the current URL to be gone, for example, it immediately sends back an HTTP response of 410 (GONE). Use this flag to mark pages which no longer exist as gone.
- proxy|P
- This flag forces the substitution part to be internally forced as a proxy request and
immediately (for example, rewriting rule processing stops here) put through the proxy module. You have to make sure that
the substitution string is a valid URI (for example, typically starting with http://hostname) which
can be handled by HTTP Server proxy module. If not you get an error from the proxy module. Use this
flag to achieve a more powerful implementation of the ProxyPass directive, to map some remote stuff
into the name space of the local server. Note: To use this functionality make sure you have the proxy module loaded into your HTTP Server configuration (for example, via LoadModule directive).
- last|L
- Stop the rewriting process here and don't apply any more rewriting rules. (This corresponds to
the Perl last command or the break command from the C language.) Use this flag to prevent the
currently rewritten URL from being rewritten further by following rules. For example, use it to
rewrite the rootpath URL ('/') to a real one, for example, '/e/www/'.
An alternative flag, [END], can be used to terminate not only the current round of rewrite processing but prevent any subsequent rewrite processing from occurring in per-directory (htaccess) context. This does not apply to new requests resulting from external redirects.
- next|N
- Re-run the rewriting process (starting again with the first rewriting rule). Here the URL to match is again not the original URL but the URL from the last rewriting rule. (This corresponds to the Perl next command or the continue command from the C language.) Use this flag to restart the rewriting process, for example, to immediately go to the top of the loop. But be careful not to create an infinite loop.
- chain|C
- This flag chains the current rule with the next rule (which itself can be chained with the following rule, etc.). This has the following effect: if a rule matches, then processing continues as usual, for example, the flag has no effect. If the rule does not match, then all following chained rules are skipped. For instance, use it to remove the ``.www'' part inside a per-directory rule set when you let an external redirect happen (where the ``.www '' part should not occur).
- type|T=MIME-type
- Force the MIME-type of the target file to be MIME-type. For instance, this can be used to simulate the mod_alias directive ScriptAlias which internally forces all files inside the mapped directory to have a MIME type of ``application/x-httpd-cgi''.
- nosubreq|NS
- 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 HTTP Server when mod_include tries to find out information about possible directory default files (index.xxx). On sub-requests it is not always useful and even sometimes causes a failure if the complete set of rules are applied. Use this flag to exclude some rules. Whenever you prefix some URLs with CGI-scripts to force them to be processed by the CGI-script, the chance is high that you will run into problems (or even overhead) on sub-requests. In these cases, use this flag.
- nocase|NC
- This makes the Pattern case insensitive, for example, there is no difference between AZ and AZ when Pattern is matched against the current URL.
- noescape|NE
- This flag prevents mod_rewrite from applying the usual URI escaping rules to the result of a rewrite. Ordinarily, special characters (%', '$', ';',) will be escaped into their hexcode equivalents ('%25', '%24', and '%3B', respectively); this flag prevents this from happening. This flag allows percent symbols to appear in the output, as in RewriteRule /foo/(.*) /bar?arg=P1\%3d$1 [R,NE] which would turn '/foo/zed' into a safe request for '/bar?arg=P1=zed'.
- qsappend|QSA
- This flag forces the rewriting engine to append a query string part in the substitution string to the existing one instead of replacing it. Use this when you want to add more data to the query string via a rewrite rule.
- qsdiscard|QSD
- When the requested URI contains a query string, and the target URI does not, the default behavior of RewriteRule is to copy that query string to the target URI. Using the [QSD] flag causes the query string to be discarded. Using [QSD] and [QSA] together will result in [QSD] taking precedence. If the target URI has a query string, the default behavior will be observed - that is, the original query string will be discarded and replaced with the query string in the RewriteRule target URI.
- passthrough|PT
- This flag forces the rewriting engine to set the URI field of the internal request_rec structure
to the value of the filename field. This flag is used to be able to post-process the output of
RewriteRule directives by Alias, ScriptAlias, Redirect, etc. - directives from other URI-to-filename
translators. A trivial example to show the semantics: If you want to rewrite /ABC to /def via the
rewriting engine of mod_rewrite and then /def to /ghi with
mod_alias:
RewriteRule ^/ABC(.*) /def$1 [PT] Alias /def /ghi
If you omit the PT flag then mod_rewrite will do its job fine, for example, it rewrites uri=/ABC/... to filename=/def/... as a full API-compliant URI-to-filename translator should do. Then mod_alias comes and tries to do a URI-to-filename transition which will not work.
Note: You have to use this flag if you want to intermix directives of different modules which contain URL-to-filename translators. The typical example is the use of mod_alias and mod_rewrite.
- skip|S=num
- This flag forces the rewriting engine to skip the next num rules in sequence when the current rule matches. Use this to make pseudo if-then-else constructs: The last rule of the then-clause becomes skip=N where N is the number of rules in the else-clause. (This is not the same as the 'chain|C' flag.)
- env|E=[!]VAR[:VAL]
- This forces an environment variable named VAR to be set to the value VAL, where VAL can contain regexp backreferences $N and %N which will be expanded. You can use this flag more than once to set more than one variable. The variables can be later dereferenced in many situations, but usually from within SSI (via <!--#echo var="VAR"-->) or CGI (for example $ENV{'VAR'}). Additionally you can dereference it in a following RewriteCond pattern via %{ENV:VAR}. Use this to strip but remember information from URLs.
- qslast|QSL
- Interpret the last (right-most) question mark as the query string delimeter, instead of the first (left-most) as normally used.
- 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.
- B
- Escape non-alphanumeric characters in backreferences before applying the transformation. The [B] flag instructs RewriteRule to escape non-alphanumeric characters before applying the transformation. mod_rewrite has to unescape URLs before mapping them, so backreferences are unescaped at the time they are applied. Using the B flag, non-alphanumeric characters in backreferences will be escaped.
- backrefnoplus|BNP
- If backreferences are being escaped, spaces should be escaped to %20 instead of +. Useful when the backreference will be used in the path component rather than the query string.
- cookie|CO=NAME:VAL
-
This flag allows you to set a cookie in the client browser when a particular RewriteRule matches. The argument consists of three required fields and four optional fields. The full syntax for the flag, including all attributes, is: [CO=NAME:VALUE:DOMAIN:lifetime:path:secure:httponly]
If a literal ':' character is needed in any of the cookie fields, an alternate syntax is available. To opt-in to the alternate syntax, the cookie "Name" should be preceded with a ';' character, and field separators should be specified as ';'.
[CO=;NAME;VALUE:MOREVALUE;DOMAIN;lifetime;path;secure;httponly]
You must declare a name, a value, and a domain for the cookie to be set.
- discardpath|DPI
- This flag causes the PATH_INFO portion of the rewritten URI to be discarded. 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.
- Handler|H=Content-handler
- This flag forces the resulting URI to be sent to the specified Content-handler for processing. For example, one might use this to force all files without a file extension to be parsed by the php handler: RewriteRule !\. - [H=application/x-httpd-php] The regular expression above - !\. - will match any request that does not contain the literal . character.
- The flags parameter can additionally be set to special [flags] for Substitution by appending
[flags] as the third argument to the RewriteRule directive. Flags is a comma separated list,
surround by square brackets, of the following flags:
Possible substitution combinations and meanings:
- Inside per-server configuration (httpd.conf) for request "GET
/somepath/pathinfo":
Given rule Resulting substitution ^/somepath(.*) otherpath$1 not supported ^/somepath(.*) otherpath$1 [R] not supported ^/somepath(.*) otherpath$1 [P] not supported ^/somepath(.*) /otherpath$1 /otherpath/pathinfo ^/somepath(.*) /otherpath$1 [R] http://thishost/otherpath/pathinfo via external redirection ^/somepath(.*) /otherpath$1 [P] 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] 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/.htaccess,
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] not supported ^localpath(.*) /otherpath$1 /otherpath/pathinfo ^localpath(.*) /otherpath$1 [R] http://thishost/otherpath/pathinfo via external redirection ^localpath(.*) /otherpath$1 [P] 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] 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
If you wanted to rewrite URLs of the form / Language /~ Realname /.../ File into /u/ Username /.../ File . Language, you would take the rewrite mapfile from above and save it under /path/to/file/map.txt. Then we only have to add the following lines to HTTP Server configuration file:
RewriteLog /path/to/file/rewrite.log
RewriteMap real-to-user txt:/path/to/file/map.txt
RewriteRule ^/([^/]+)/~([^/]+)/(.*)$ /u/${real-to-user:$2|nobody}/$3.$1