7. RewriteCond¶
Snore on in your front row seatLet not my voice disturb the wordless heaven your eyes have found—James Kirkup, To An Old Lady Asleep At A Poetry Reading
The RewriteCond directive attaches additional conditions on a
RewriteRule, and may also set backreferences that may be used in the
rewrite target.
One or more RewriteCond directives may precede a RewriteRule
directive. That RewriteRule is then applied only if the current state
of the URI matches its pattern, and all of these conditions are met.
The RewriteCond directive has the following syntax:
RewriteCond TestString CondPattern [Flag]
The arguments have the following meaning:
- TestString
Any string or variable to be tested for a match.
- CondPattern
A regular expression or other expression to be compared against the TestString.
- Flag
One or more flags which modify the behavior of the condition.
These definitions will be expanded in the sections below.
7.1. TestString¶
TestString is a string which can contain the following expanded constructs in addition to plain text:
- RewriteRule backreferences
These are backreferences of the form $N (0 <= N <= 9). $1 to $9 provide access to the grouped parts (in parentheses) of the pattern, from the RewriteRule which is subject to the current set of RewriteCond conditions. $0 provides access to the whole string matched by that pattern.
- RewriteCond backreferences
These are backreferences of the form %N (0 <= N <= 9). %1 to %9 provide access to the grouped parts (again, in parentheses) of the pattern, from the last matched RewriteCond in the current set of conditions. %0 provides access to the whole string matched by that pattern.
- RewriteMap expansions
These are expansions of the form ${mapname:key|default}. See the documentation for 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:
|
|
Connection & request:
|
|
Server internals:
|
|
Date and time:
|
|
Specials:
|
|
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 elsewhere in the Manual or in the CGI specification.
SERVER_NAME and SERVER_PORT depend on the values of UseCanonicalName and UseCanonicalPhysicalPort respectively.
Those that are special to mod_rewrite include those below.
- IS_SUBREQ
Will contain the text “true” if the request currently being processed is a sub-request, “false” otherwise. Sub-requests may be generated by modules that need to resolve additional files or URIs in order to complete their tasks.
- API_VERSION
This is the version of the Apache httpd module API (the internal interface between server and module) in the current httpd build, as defined in include/ap_mmn.h. The module API version corresponds to the version of Apache httpd in use (in the release version of Apache httpd 1.3.14, for instance, it is 19990320:10), but is mainly of interest to module authors.
- THE_REQUEST
The full HTTP request line sent by the browser to the server (e.g., “GET /index.html HTTP/1.1”). This does not include any additional headers sent by the browser. This value has not been unescaped (decoded), unlike most other variables below.
- REQUEST_URI
The path component of the requested URI, such as “/index.html”. This notably excludes the query string which is available as its own variable named QUERY_STRING.
- REQUEST_FILENAME
The full local filesystem path to the file or script matching the request, if this has already been determined by the server at the time REQUEST_FILENAME 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 to map the request to a file.
- HTTPS
Will contain the text “on” if the connection is using SSL/TLS, or “off” otherwise. (This variable can be safely used regardless of whether or not
mod_sslis loaded).- REQUEST_SCHEME
Will contain the scheme of the request (usually “http” or “https”). This value can be influenced with ServerName.
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:
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 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 field of request_rec).
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) SCRIPT_FILENAME and REQUEST_FILENAME 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
REQUEST_URI 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:REQUEST_FILENAME} to determine the final value of
REQUEST_FILENAME.
%{ENV:variable}, where variable can be any environment variable, is
also available. This is looked-up via internal Apache httpd structures
and (if not found there) via getenv() from the Apache httpd server
process.
%{SSL:variable}, where variable is the name of an SSL environment
variable, can be used whether or not mod_ssl is loaded, but will always
expand to the empty string if it is not. Example:
%{SSL:SSL_CIPHER_USEKEYSIZE} may expand to 128.
%{HTTP:header}, where header can be any HTTP MIME-header name, can
always be used to obtain the value of a header sent in the HTTP request.
Example: %{HTTP:Proxy-Connection} is the value of the HTTP header
Proxy-Connection:.
If an 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.
%{LA-U:variable} can be used for look-aheads which perform an internal
(URL-based) sub-request to determine the final value of variable. This
can be used to access variable for rewriting which is not available at
the current stage, but will be set in a later phase.
For instance, to rewrite according to the REMOTE_USER variable from
within the per-server context (httpd.conf file) you must use
%{LA-U:REMOTE_USER} - 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 file) via the Fixup phase of the API and because the
authorization phases come before this phase, you just can use
%{REMOTE_USER} in that context.
%{LA-F:variable} can be used to perform 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.
7.2. CondPattern¶
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:
You can prefix the pattern string with a ‘!’ character (exclamation mark) to specify a non-matching pattern.
You can perform lexicographical string comparisons:
- ‘<CondPattern’ (lexicographically precedes)
Treats the CondPattern as a plain string and compares it lexicographically to TestString. True if TestString lexicographically precedes CondPattern.
# Only apply the rule if the requested host sorts before "m" # (i.e. hostnames starting with a-l) RewriteCond %{HTTP_HOST} <m RewriteRule ^ /first-half-of-alphabet [L]
- ‘>CondPattern’ (lexicographically follows)
Treats the CondPattern as a plain string and compares it lexicographically to TestString. True if TestString lexicographically follows CondPattern.
# Redirect if the requested URI sorts after /wiki/ RewriteCond %{REQUEST_URI} >/wiki/ RewriteRule ^ /later-section [L]
- ‘=CondPattern’ (lexicographically equal)
Treats the CondPattern as a plain string and compares it lexicographically to TestString. True if TestString is lexicographically equal to CondPattern (the two strings are exactly equal, character for character). If CondPattern is “” (two quotation marks) this compares TestString to the empty string.
# Match only the exact hostname "www.example.com" RewriteCond %{HTTP_HOST} =www.example.com RewriteRule ^ /main-site/$0 [L] # Check whether the query string is empty RewriteCond %{QUERY_STRING} ="" RewriteRule ^/search$ /search?q=default [L]
- ‘<=CondPattern’ (lexicographically less than or equal to)
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).
# Match API versions up through "v3" (v1, v2, v3 but not v4) RewriteCond %{HTTP:X-API-Version} <=v3 RewriteRule ^ /legacy-api%{REQUEST_URI} [L]
- ‘>=CondPattern’ (lexicographically greater than or equal to)
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).
# Match API versions v3 and above RewriteCond %{HTTP:X-API-Version} >=v3 RewriteRule ^ /modern-api%{REQUEST_URI} [L]
Note
These comparisons are lexicographic (byte-by-byte string ordering),
not numeric. That means "9" > "10" is true, because "9"
sorts after "1". If you need numeric comparisons, use the
integer operators (-eq, -gt, etc.) described next.
Warning
Known bug in case-sensitive < and > operators
The implementation of the case-sensitive < and > operators
(the compare_lexicography() function in mod_rewrite.c) has a
long-standing bug (Bug 40453): it
compares string lengths first. When strings differ in length,
the longer string is always considered “greater” regardless of
content. This means "AAA" > "B" evaluates as true, which
is incorrect.
Workarounds:
Use the case-insensitive variants (
[NC]flag or the<=/>=forms that usestrcasecmp) — these are not affected.Use the
exprsyntax in aRewriteCond, which usesap_exprand handles comparisons correctly:RewriteCond expr "%{REQUEST_URI} < '/m'"
This bug has been present since at least httpd 2.2 and remains unfixed as of 2.4.62.
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.
# Only apply to requests on port 8080 RewriteCond %{SERVER_PORT} -eq 8080 RewriteRule ^ /dev-portal%{REQUEST_URI} [L]
- ‘-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.
# Redirect if the Content-Length is 10MB or more RewriteCond %{HTTP:Content-Length} -ge 10485760 RewriteRule ^ /upload-too-large [R=413,L]
- ‘-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.
# Route to the new server if the requested port is above 9000 RewriteCond %{SERVER_PORT} -gt 9000 RewriteRule ^ http://newserver.example.com%{REQUEST_URI} [R,L]
- ‘-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.
# Serve a lightweight page if the client says it can only accept # small responses RewriteCond %{HTTP:Max-Response-Size} -le 1024 RewriteRule ^/report$ /report-summary [L]
- ‘-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.
# If the hour is before 06:00, show the overnight maintenance page RewriteCond %{TIME_HOUR} -lt 06 RewriteRule ^ /overnight.html [L]
You can perform various file attribute tests:
- ‘-d’ (is directory)
Treats the TestString as a pathname and tests whether or not it exists, and is a directory.
# If the request maps to an existing directory, let it through RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L]
- ‘-f’ (is regular file)
Treats the TestString as a pathname and tests whether or not it exists, and is a regular file.
# If the file doesn't exist, route to the front controller RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ /index.php [L]
- ‘-F’ (is existing file, via subrequest)
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!
# Only rewrite if the target is actually accessible RewriteCond /var/www/html%{REQUEST_URI} -F RewriteRule ^/mirror/(.*)$ /$1 [L]
- ‘-H’ (is symbolic link, bash convention)
See -l.
- ‘-l’ (is symbolic link)
Treats the TestString as a pathname and tests whether or not it exists, and is a symbolic link. May also use the bash convention of -L or -h if there’s a possibility of confusion such as when using the -lt or -le tests.
# If the request points to a symlink, redirect to the real path RewriteCond %{REQUEST_FILENAME} -l RewriteRule ^(.*)$ /real$1 [R,L]
- ‘-L’ (is symbolic link, bash convention)
See -l.
- ‘-s’ (is regular file, with size)
Treats the TestString as a pathname and tests whether or not it exists, and is a regular file with size greater than zero.
# Serve cached content only if the cache file is non-empty RewriteCond /var/cache/html%{REQUEST_URI} -s RewriteRule ^(.*)$ /var/cache/html$1 [L]
- ‘-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!
# Fall back to a mirror if the local URL would 404 RewriteCond %{REQUEST_URI} !-U RewriteRule ^(.*)$ http://mirror.example.com$1 [R,L]
- ‘-x’ (has executable permissions)
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 requested file is executable, run it as CGI RewriteCond %{REQUEST_FILENAME} -x RewriteRule ^/scripts/(.*)$ /cgi-bin/$1 [L]
Note:
All of these tests can also be prefixed by an exclamation mark (‘!’) to negate their meaning.
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]
Flag
You can also set special flags for CondPattern by appending [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)
This makes the test case-insensitive - differences between ‘A-Z’ and ‘a-z’ are ignored, 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’ (or next condition)
Use this to combine rule conditions with a local OR instead of the implicit AND. Typical example:
RewriteCond %{REMOTE_HOST} ^host1 [OR]
RewriteCond %{REMOTE_HOST} ^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.
- ‘novary|NV’ (no vary)
If an 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.
7.3. Examples¶
The following examples show RewriteCond in common real-world
scenarios. Many of these appear again in Recipes with
additional discussion.
7.3.1. Matching query strings¶
RewriteRule only matches against the URL-path — it never sees the
query string. To test query string content, use RewriteCond with
%{QUERY_STRING}:
# Redirect old query-string-based URLs to clean paths
RewriteCond %{QUERY_STRING} ^id=([0-9]+)$
RewriteRule ^/product$ /product/%1? [R=301,L]
This turns /product?id=42 into /product/42. The trailing ?
in the substitution strips the original query string (without it, the
query string is passed through by default). The %1 backreference
comes from the RewriteCond capture group, not from RewriteRule.
7.3.2. Hostname-based routing¶
Test the Host: header to apply rules only to specific hostnames:
# Redirect www to non-www
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$ https://example.com$1 [R=301,L]
The [NC] flag on the condition makes the hostname comparison
case-insensitive.
7.3.3. File and directory existence¶
The -f and -d tests check whether a path exists on disk. This
is the basis of the front-controller pattern:
# If the request isn't an existing file or directory, route to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php [L]
The ! negates the test. Both conditions must be true (the default
is AND), so the rule fires only when the request matches neither an
existing file nor an existing directory.
Note: FallbackResource (see FallbackResource) does the same
thing in a single line. Use RewriteCond !-f only when you need
additional conditions or URL transformations that FallbackResource
can’t express.
7.3.4. Time-based rules¶
The TIME_* variables let you vary behavior by time of day, day of
week, or date:
# Maintenance window: redirect all traffic between 2 AM and 4 AM
RewriteCond %{TIME_HOUR} ^0[2-3]$
RewriteRule !^/maintenance\.html$ /maintenance.html [R=302,L]
The RewriteRule pattern uses ! to exclude the maintenance page
itself — without this, you’d create an infinite redirect loop.
7.3.5. Requiring HTTPS¶
Test whether the connection is secure:
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]
Or, if you’re behind a load balancer that terminates TLS and forwards
X-Forwarded-Proto:
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]
Note the syntax %{HTTP:HeaderName} for testing arbitrary HTTP
request headers.
7.3.6. Combining conditions with OR¶
By default, multiple RewriteCond directives are ANDed. Use the
[OR] flag for OR logic:
# Block two specific user agents
RewriteCond %{HTTP_USER_AGENT} BadBot [NC,OR]
RewriteCond %{HTTP_USER_AGENT} EvilScraper [NC]
RewriteRule ^ - [F]
The [F] flag returns a 403 Forbidden. The rule fires if either
condition matches.