SEM Labs

Handcrafted Pixels, Code & Title Tags

mod_rewrite Quick Reference and Cheat Sheet

This reference is designed to cover all aspects of mod_rewrite with minimal detail. It will be of most use to those who know a bit about mod_rewrite and pros who just need a quick reference.

Apache HTTP Server Logo

As the reference is a little meaty to fit on this page, you will find links to a full screen version and PNG version below.

Table of Contents

Directives
mod_rewrite directives define how URLs should be modified and modify the module's settings.
Directive Name Arguments Description
RewriteEngine on
off
Turns runtime mod_rewrite processing on/off.
RewriteOptions inherit - forces inheritance of the parent options
MaxRedirects=integer - number of redirects permitted per request (defaults to 10)
Sets options for current directory.
RewriteLog file-path Path (relative to server root) where log file will be saved.
RewriteLogLevel 0 - 10 Level of errors to be logged (defaults to 0).
RewriteLock file-path Path (local) of a synchronisation lockfile.
RewriteMap MapName MapType:MapSource Name type and path of a Rewriting Map.
RewriteBase URL-path Path to be used as prefix in rewrite rules.
RewriteCond test-string pattern [flags] Condition for a RewriteRule.
RewriteRule pattern substitution [flags] Descriptions of how URLs should be re-written.
Pattern Syntax
The pattern argument of the RewriteCond and RewriteRule directives test strings using regular expression.
Symbol Description Example
Anchors
^ Tests a pattern against the start of a string. RewriteRule ^index.html -
$ Tests a pattern against the end of a string. RewriteRule -page.html$ -
Operators
! Tests if a pattern is flase. RewriteRule !index.html -
Grouping
(pattern) Groups a matched portion into a backreference. RewriteRule ^index.php?page=(home)$ page/$1
Text
a|b|c Tests against multiple patters. RewriteRule ^index.html|about.html$ -
[abc] Tests against a range of characters. Will accept logical ranges, e.g. a-z (basic Latin), 0-9 (digit), \x7f-\xff (Unicode). RewriteRule ^[a-z0-9]+$ -
[^abc] Tests against a range, negatively. RewriteRule ^[^a-z]+$ -
Quantifiers
a? Zero or one. RewriteRule ^[a-z]?$ -
a* Zero or more than. RewriteRule ^[0-9]*$ -
a+ One or more. RewriteRule ^[0-9a-z]+$
a{2} An exact length. RewriteRule ^[a-z]{10}$ -
a{2,} Equal or more than in length. RewriteRule ^[a-z]{5,}$ -
a{2,4} Between x and y in length. RewriteRule ^[a-z0-9]{1,9}$ -
Ungreedy
? When using quantifiers, stops matching when the preceding part of the pattern matches the current part of the string. RewriteRule ^page-[a-z-.]+?.html$
Escaping
\ To escape characters that may otherwise be considered special characters. RewriteRule \$dollar.html -
Substitution Syntax
The substitution argument of the RewriteRule directive defines the URL a request should be directed to.
Symbol Description Example
- Defines a RewriteRule in which no substitution shall occur. RewriteRule ^old-page.html$ - [G]
Backreferences
Backreference are the matched text within a grouping '(...)' of the corresponding pattern.
Syntax Description Example
%n Backreference to groups in RewriteCond pattern [0-9], 0 is equal to the entire match. RewriteCond %{QUERY_STRING} ^prod=([a-z0-9-]+)&cat
RewriteRule ^product.php product.php?prod=%1
$n Backreference to groups in RewriteRule pattern [0-9], 0 is equal to the entire match. RewriteRule ^index.py?name=([a-z-]+)&cat=([0-9]+)$ $1/$2
Mapping Functions
${mapname:key|default} Call to function in a RewriteMap. ${example-map:$1|value}
RewriteCond Operators
The pattern argument of the RewriteCond directive is supplemented with a number of special operators.
Operator Description Example
< Is lexically lower. RewriteCond directory-a <directory-b
> Is lexically greater. RewriteCond directory-b >directory-a
= Is lexically equal. RewriteCond directory-c =directory-c
-d Is a directory. RewriteCond /directory/ -d
-f Is a file. RewriteCond /path/index.html -f
-s Tests if the test-string exists and has a file size of more than 0 bytes. RewriteCond /path/index.html -s
-F Is existing file via subrequest. RewriteCond /path/index.html -F
-U Is existing URL via subrequest. RewriteCond /path/index.html -U
RewriteCond Flags
The RewriteCond directive can be supplemented with a number of comma separated flags to modify the nature of the condition.
Flag Description Example
NC Test of test-string and pattern becomes case-insensitive. RewriteCond localhost LOCALHOST [NC]
OR Combines rules with OR as opposed to AND. RewriteCond %{REMOTE_HOST} ^localhost [OR]
RewriteCond %{REMOTE_HOST} ^remotehost
RewriteRule Flags
The RewriteRule directive can be supplemented with a number of comma separated flags to modify the nature of the rule.
Flag Description Example
C Chain the current rule with the next rule. If a rule matches processing continues, else all further chained rules are ignored. RewriteRule ^index.html$ substituted.html [C]
RewriteRule ^substituted.html$ further-substituted.html [C]
RewriteRule ^further-substituted.html$ final-substitution.html
CO=name:value:domain[lifetime:path] Forces the response to be a specified MIME-type. RewriteRule index.html - [CO=foo:bar:domain.com:14400:/]
E=VAR:VAL Set an environmental variable where VAR is the name of the variable and VAL is the value. The value may contain regular expression and backreferences. RewriteRule .* - [E=foo:bar]
F Returns a 403 response (forbidden). RewriteRule ^private-area - [F]
G Returns a 410 response (gone). RewriteRule ^old-page.html - [G]
H=handler Specifies what should handle the request. RewriteRule index.cgi - [H=cgi-script]
L Stops the rewriting process - no more rules are processed. RewriteRule ^.* index.py?request=$0 [L]
N Start the rewriting process again from the first rule with the current substituted URL. RewriteRule ^index.html$ substituted.html [N]
NC This makes the Pattern case-insensitive. RewriteRule ^INDEX.HTML$ index.html [NC]
NE By default special characters (%, $ etc.) are replaced with their hexadecimal equivalents. The NE flag turns this escaping off. RewriteRule ^index.html$ hello%world.html [NE]
NS The rule will be skipped if the request is an internal sub-request, i.e. if substitutions have already been made. RewriteRule ^.*$ further-substituted.html [NS]
P Requested is routed through Apache proxy module. The substitution must begin with a valid host. RewriteRule ^proxy.html http://proxyhost/proxy.html [P]
PT Facility to allow the post-processing of RewriteRule directives. RewriteRule ^hidden/ secret/ [PT]
Alias /secret /var/www/secret-files
QSA An acronym for query string append, this flag forces the query string part of existing one to be appened to the substitution. RewriteRule ^.*$ further-substituted.html [NS]
R[=code] Forces a redirect to the substitution URL. Code (HTTP header status code) may be in the range of 300-400 and defaults to 302 (moved temporarily). Using 301 (moved permanently) will cause search engines to transfer the target of incoming links. RewriteRule ^olg-page.html$ new-page.html [R=301]
S[=integer] When the current rule matches, the next specified number of rules will be skipped. RewriteRule ^index.html$ new.html [S]
T=MIME-type Forces the response to be a specified MIME-type. RewriteRule ^jpeg/(.+)$ jpeg.pl?=src=$1 [T=image/jpeg]
Variables
mod_rewrite has a number of variables, which can be used in the RewriteCond text-string and the RewriteRule substitution arguments.
Name Description Example Output
%{HTTP_USER_AGENT} The user agent string of the client that sent the request. Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.3) Gecko/2008101315 Linux Mint/6 (Felicia) Firefox/3.0.3
%{HTTP_REFERER} The refering document. http://localhost/path/
%{HTTP_COOKIE} The contents of any cookies set for the request. SID=58301702dfcb380ebe1e93f28bcbbc1a
%{HTTP_FORWARDED} Typically the IP address of the client that is using a proxy server. 123.123.123.123
%{HTTP_HOST} The name of the remove host being requested. localhost
%{HTTP_PROXY_CONNECTION} Timeout status of HTTP proxy connection. keep-alive
%{HTTP_ACCEPT} Lists which media types are acceptable for the response. text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
%{REMOTE_ADDR} IP address of the client that sent the request. 123.123.123.123
%{REMOTE_HOST} IP address of the client that sent the request. 123.123.123.123
%{REMOTE_USER} Username of access authenticated client. bob
%{REMOTE_IDENT} The user making the request as specified by identd or similar daemon. =?UTF-8?b?0YHQsNGFNORDgA==?=
%{REQUEST_METHOD} The method used by the client in the request. See rfc2616 for HTTP 1.1 request methods. GET
%{SCRIPT_FILENAME} The full file-path to the file/directory being requested. /var/www/path/script.py
%{PATH_INFO} The remainder of the request URL's path. /
%{QUERY_STRING} Content of the query string, i.e. part of the URL after the question mark and before the anchor. ?foo=bar&var=64
%{AUTH_TYPE} The type of authentication used (if any). Typically basic or digest. basic
%{DOCUMENT_ROOT} The root directory as defined by the DocumentRoot directive. /var/www/
%{SERVER_ADMIN} The email address for the server administrator. webmaster@localhost
%{SERVER_NAME} The servers host name, DNS alias or IP address. localhost
%{SERVER_ADDR} The IP address of the server handling the request. 127.0.0.1
%{SERVER_PORT} The port number on the server that is handling the request. 80
%{SERVER_PROTOCOL} The name and the version of the protocol of the request. HTTP/1.1
%{SERVER_SOFTWARE} The name and version of the software handling the request. Apache/2.2.9 (Ubuntu) PHP/5.2.6-2ubuntu4.2 with Suhosin-Patch
%{TIME_YEAR} Four digit representation of the year. 2009
%{TIME_MON} Two digit representation of the month. 07
%{TIME_DAY} Two digit representation day of the month. 04
%{TIME_HOUR} Two digit representation of the hour. 02
%{TIME_MIN} Two digit representation of the minute. 34
%{TIME_SEC} Two digit representation of the second. 54
%{TIME_WDAY} One digit representation of the day of the week, 1-7, Monday is 1. 6
%{TIME} Current timestamp. 20090704023524
%{API_VERSION} Apache API version. 20051115:15
%{THE_REQUEST} The full request method header. GET /path/script.py HTTP/1.1
%{REQUEST_URI} The full URL requested. /path/script.py
%{REQUEST_FILENAME} The full filename requested. /path/script.py
%{IS_SUBREQ} true (string) when if the current request is a sub-request. false
Other Variables
mod_rewrite can also access a number of special variables.
Syntax Description Example
%{HTTP:name} Access to HTTP request headers. %{HTTP:Accept-Charset}
%{ENV:name} Access to environmental variables. %{ENV:APACHE_PID_FILE}
%{SSL:name} Access to mod_ssl variables. %{SSL:SSL_SERVER_CERT}
%{LA-U:name} Access to positive URL-based look-ahead variables. %{LA-U:REMOTE_USER}
%{LA-F:name} Access to positive file-path-based look-ahead variables. %{LA-F:REMOTE_USER}

If you need help with mod_rewrite, drop by the very helpful mod_rewrite Forum.

Comments

Jake Rocheleau Replied at 9:47 PM on 5 Jul 2009

This is great, I'm always using the Mod_Rewrite feature but never knew there were so many variables to use. Thanks for the share!

David Replied at 4:10 PM on 8 Jul 2009

There are actually quite a lot of other variables that are not listed in the Apache reference, which I have not listed as they are not commonly populated with a value.

terry Replied at 9:40 AM on 7 Jul 2009

The directives section should have included examples too. Otherwise, good for those who are unfamiliar with using mod_rewrite and Apache web server.

stratosg Replied at 11:47 AM on 11 Jul 2009

Wow man! This is an excellent reference... It can really save time some times... Bookmarked ;)

Pete Moore Replied at 7:28 AM on 26 May 2011

A comprehensive documentation of all the variables for Mod_rewrite on Apache. Thanks for sharing - will save me a lot of time next time!

Post Comment

Thin comments left for links will be deleted.

Entry Info

Categories