FREE THOUGHT · FREE SOFTWARE · FREE WORLD

Mod_Rewrite Variables Cheatsheet

mod_rewrite cheatsheet for .htaccess rewritesWe've figured out what mod_rewrite variables look like so we can create rewrite rules and condition patterns based on the actual value. This cheatsheet is where we'll lay them all out for quick reference. This cheatsheet changed my life.

Here the focus is on identifying mod_rewrite variables and defining the limits of the module by checking the mod_rewrite source code.

Apache Mod_Rewrite Variables

HTTP Variables

SSL Variables

Variable Values and Examples


API_VERSION: 20020903:12
RewriteCond %{API_VERSION} ^(.*)$
RewriteRule .* https://www.askapache.com?API_VERSION=%1 [R=307,L]

AUTH_TYPE: Digest
RewriteRule .* - [E=IN_AUTH_TYPE:%{AUTH_TYPE}]
RequestHeader set AUTH_TYPE "%{IN_AUTH_TYPE}e"

CACHE_CONTROL: max-age=0
RewriteCond %{ENV:CACHE_CONTROL} no-cache [NC]
RewriteRule . %{REQUEST_URI}?nocache [L]

CONNECTION: keep-alive

CONTENT_LENGTH: (null)
RewriteCond %{REQUEST_METHOD} =POST
RewriteCond %{HTTP:Content-Length}%{CONTENT_LENGTH} ^$
RewriteRule .* - [F,NS,L]

CONTENT_TYPE: (null)

DOCUMENT_ROOT: /web/webroot/askapache.com
RewriteCond %{DOCUMENT_ROOT}/cache%{REQUEST_URI}/index.html -f
RewriteRule . /cache%{REQUEST_URI}/index.html

HOST: www.askapache.com
RewriteCond %{HTTP_HOST} !^www\.askapache\.com$ [NC]
RewriteRule . https://www.askapache.com%{REQUEST_URI} [R=301,L]

HTTP:
RewriteCond %{HTTP:Accept-Encoding} gzip [NC]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}\.gz -f
RewriteRule . %{REQUEST_URI}.gz [L]

HTTP_ACCEPT: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

HTTP_COOKIE: __qca=1176541205adf28-5553185; ASKAPACHEID=fdadfa4f33e62a878468; __utmc=1df3893
RewriteCond %{HTTP_COOKIE} ^.*autostart=on.*$
RewriteRule ^(.*)\.swf$ /$1?autostart=true [NE,L]

HTTP_HOST: www.askapache.com

HTTP_REFERER: https://www.askapache.com/pro/mod_rewrite/catch.php?k=i
RewriteCond %{HTTP_REFERER} badhost [NC]
RewriteRule . - [F]

HTTP_USER_AGENT: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9) Firefox/3.0.1
RewriteCond %{HTTP_USER_AGENT} ^.*(Android|2\.0 MMP|240x320|AvantGo|BlackBerry|Blazer|Cellphone|Danger|DoCoMo|EudoraWeb|hiptop|IEMobile|iPhone).*$ [NC]
RewriteRule ^(.+)$ /mobile/$1 [L]

IS_SUBREQ: false

KEEP_ALIVE: 300

PATH: /bin:/usr/bin:/sbin:/usr/sbin

QUERY_STRING: k=i
RewriteCond %{QUERY_STRING} showtime [NC]
RewriteCond T:%{TIME}_TY:%{TIME_YEAR}_TMO:%{TIME_MON}_TWD:%{TIME_WDAY}_TD:%{TIME_DAY}_TH:%{TIME_HOUR}_TMI:%{TIME_MIN}_TS:%{TIME_SEC} ^(.*)$
RewriteRule .* http://%{HTTP_HOST}%{REQUEST_URI}?time=%1 [R,L]

REMOTE_ADDR: 22.162.134.211
RewriteCond %{REMOTE_ADDR} !^22\.162\.134\.211$
RewriteRule . https://www.askapache.com/maintenance-in-progress.html [R=307,L]

REMOTE_HOST: 22.162.134.211

REMOTE_PORT: 4220

REMOTE_USER: askapache
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]

REQUEST_FILENAME: /web/webroot/askapache.com/pro/mod_rewrite/index.php

REQUEST_METHOD: GET
RewriteCond %{REQUEST_METHOD} !^(POST|GET|HEAD|PROPFIND|OPTIONS)$
RewriteRule .* - [F,L]

REQUEST_PROTOCOL: HTTP/1.1
RewriteCond %{REQUEST_PROTOCOL} !^HTTP/(0\.9|1\.[01])$
RewriteRule . [F,L]

REQUEST_URI: /pro/mod_rewrite/index.php
RewriteCond %{REQUEST_URI} ^(robots\.txt|favicon\.ico)$ [NC]
RewriteRule . - [S=1]
RewriteCond %{HTTP_HOST} ^www
RewriteRule .* http://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

SCRIPT_FILENAME: /web/webroot/askapache.com/pro/mod_rewrite/index.php

SCRIPT_GROUP: daemong

SCRIPT_URI: https://www.askapache.com/pro/mod_rewrite/index.php

SCRIPT_URL: /pro/mod_rewrite/index.php

SCRIPT_USER: askapache

SERVER_ADDR: 208.113.134.190

SERVER_ADMIN: webmaster@askapache.com

SERVER_NAME: www.askapache.com

SERVER_PORT: 80

SERVER_PROTOCOL: HTTP/1.1

SERVER_SOFTWARE: Apache/2.0.61 (Unix) PHP/5.5 OpenSSL/0.9.7e

THE_REQUEST: GET /pro/mod_rewrite/index.php?k=i HTTP/1.1
RewriteCond %{THE_REQUEST} ^(GET|POST) /.*?(s|search)=(.+) HTTP/ [NC]
RewriteRule .* https://www.askapache.com/search/%3/? [R=302,L,NE]

TIME: 20080915152142
RewriteCond %{QUERY_STRING} showtime [NC]
RewriteCond T:%{TIME}_TY:%{TIME_YEAR}_TMO:%{TIME_MON}_TWD:%{TIME_WDAY}_TD:%{TIME_DAY}_TH:%{TIME_HOUR}_TMI:%{TIME_MIN}_TS:%{TIME_SEC} ^(.*)$
RewriteRule .* http://%{HTTP_HOST}%{REQUEST_URI}?time=%1 [R,L]

TIME_DAY: 15

TIME_HOUR: 15

TIME_MIN: 21

TIME_MON: 09

TIME_SEC: 42

TIME_WDAY: 1

TIME_YEAR: 2008

UNIQUE_ID: qOr5tEBvcm8AAE-VoiUAAAAQ

HTTPS: off
RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

SSL_CIPHER: DHE-RSA-AES256-SHA

SSL_CIPHER_ALGKEYSIZE: 256

SSL_CIPHER_EXPORT: false

SSL_CIPHER_USEKEYSIZE: 256

SSL_CLIENT_VERIFY: NONE

SSL_PROTOCOL: TLSv1

SSL_SERVER_A_KEY: rsaEncryption

SSL_SERVER_A_SIG: sha1WithRSAEncryption

SSL_SERVER_CERT: -----BEGIN CERTIFICATE----- ... MIIFkTC ... -----END CERTIFICATE-----

SSL_SERVER_I_DN: /C=US/ST=Arizona/L=Scottsdale/O=Starfield Technologies, Inc./OU=http://certificates.starfieldtech.com/repository/CN=Starfield Secure Certification Authority/serialNumber=10688435

SSL_SERVER_I_DN_C: US

SSL_SERVER_I_DN_CN: Starfield Secure Certification Authority

SSL_SERVER_I_DN_L: Scottsdale

SSL_SERVER_I_DN_O: Starfield Technologies, Inc.

SSL_SERVER_I_DN_OU: http://certificates.starfieldtech.com/repository

SSL_SERVER_I_DN_ST: Arizona

SSL_SERVER_M_SERIAL: 042840B88A2352

SSL_SERVER_M_VERSION: 3

SSL_SERVER_S_DN: /O=www.askapache.com/OU=Domain Control Validated/CN=www.askapache.com

SSL_SERVER_S_DN_CN: www.askapache.com

SSL_SERVER_S_DN_O: www.askapache.com

SSL_SERVER_S_DN_OU: Domain Control Validated

SSL_SERVER_V_END: Jul 14 16:53:43 2012 GMT

SSL_SERVER_V_START: Jul 14 20:25:17 2010 GMT

SSL_SESSION_ID: 4184083DD1C74547553018174950D88987BD7ED03CE54EBB6638539C34814376

SSL_VERSION_INTERFACE: mod_ssl/2.2.16

SSL_VERSION_LIBRARY: OpenSSL/0.9.8e-fips-rhel5

Htaccess Time Cheatsheet

#      300   5 MIN
#      600  10 MIN
#      900  15 MIN
#     1800  30 MIN
#     2700  45 MIN
#     3600   1 HR
#     7200   2 HR
#    10800   3 HR
#    14400   4 HR
#    18000   5 HR
#    36000  10 HR
#    39600  11 HR
#    43200  12 HR
#    46800  13 HR
#    50400  14 HR
#    54000  15 HR
#    86400   1 DAY
#   172800   2 DAY
#   259200   3 DAY
#   345600   4 DAY
#   432000   5 DAY
#   518400   6 DAY
#   604800   1 WEEK
#  1209600   2 WEEK
#  1814400   3 WEEK
#  2419200   4 WEEK
#  4838400   2 MONTH
#  7257600   3 MONTH
#  9676800   4 MONTH
# 12096000   5 MONTH
# 14515200   6 MONTH
# 16934400   7 MONTH
# 19353600   8 MONTH
# 21772800   9 MONTH
# 24192000  10 MONTH
# 26611200  11 MONTH
# 29030400  12 MONTH

Mod_Rewrite Directives

For a broader mod_rewrite cheat sheet, check this printable cheat sheet.

RewriteEngine
RewriteEngine on|off
On or Off to enable or disable (default) the whole rewriting engine
RewriteOptions
RewriteOptions Options
List of option strings to set
RewriteBase
RewriteBase URL-path
the base URL of the per-directory context
RewriteCond
RewriteCond TestString CondPattern
an input string and a to be applied regexp-pattern
RewriteRule
RewriteRule Pattern Substitution [flags]
an URL-applied regexp-pattern and a substitution URL
RewriteMap
RewriteMap MapName MapType:MapSource
a mapname and a filename
RewriteLock
RewriteLock file-path
the filename of a lockfile used for inter-process synchronization
RewriteLog
RewriteLog file-path
the filename of the rewriting logfile
RewriteLogLevel
RewriteLogLevel Level
the level of the rewriting logfile verbosity (0=none, 1=std, .., 9=max)

Rules and Conditions Processing Order

  1. The Pattern of the RewriteRule (^/.*$) is checked first.
  2. If the pattern matches, then the RewriteCond's are checked.
  3. If the RewriteConditions also match, the RewriteRule is applied.

RewriteRule Flags

C
Using the [Chain], or [C] flag, allows you to indicate that several rules should be chained together as a single logical transation. This is usually used when a transformation is sufficiently complicated to warrant breaking into several smaller steps.
CO
cookie|CO=Name:Value:Domain[:Lifetime[:Path]]

This sets a cookie on the client's browser. The cookie's name is specified by NAME and the value is VAL. The domain field is the domain of the cookie, such as '.apache.org',the optional lifetime is the lifetime of the cookie in minutes, and the optional path is the path of the cookie.
E
'env|E=VAR:VAL' (set environment variable)

RewriteRule (root|cmd)\.exe - [E=worm:nimda]
F
'forbidden|F' (force URL to be forbidden)

G
'gone|G' (force URL to be gone)

H
'handler|H=Content-handler' (force Content handler)

L
'last|L' (last rule)

N
'next|N' (next round)

NC
'nocase|NC' (no case)

NE
'noescape|NE' (no URI escaping of output)

NS
'nosubreq|NS' (not for internal sub-requests)

P
'proxy|P' (force proxy)

PT
'passthrough|PT' (pass through to next handler)

QSA
'qsappend|QSA' (query string append)

R
'redirect|R  [=code]' (force redirect)

S
'skip|S=num' (skip next rule(s))

This flag forces the rewriting engine to skip the next num rules in sequence, if 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!)
T
'type|T=MIME-type' (force MIME type)

Force the MIME-type of the target file to be MIME-type. This can be used to set up the content-type based on some conditions. For example, the following snippet allows .php files to be displayed by mod_php if they are called with the .phps extension:

RewriteRule Special Variables

  1. ENV_
  2. SSL_
  3. HTTP_
  4. LA-U_
  5. LA-F_

RewriteCond Tests

  • -f - FILE_EXISTS
  • -s - FILE_SIZE
  • -l - FILE_LINK
  • -d - FILE_DIR
  • -x - FILE_XBIT
  • -U - LU_URL
  • -F - LU_FILE
  • > - STR_GT
  • < - STR_LT
  • = - STR_EQ

Mod_Rewrite Variables, from Source

  • API_VERSION - "%d:%d",MODULE_MAGIC_NUMBER_MAJOR,MODULE_MAGIC_NUMBER_MINOR)
  • APR_FINFO_USER
  • AUTH_TYPE - ap_auth_type
  • DOCUMENT_ROOT - ap_document_root(r)
  • HTTP_ACCEPT - lookup_header("Accept", ctx)
  • HTTP_COOKIE - lookup_header("Cookie", ctx)
  • HTTP_FORWARDED - lookup_header("Forwarded", ctx)
  • HTTP_HOST - lookup_header("Host", ctx)
  • HTTP_PROXY_CONNECTION - lookup_header("Proxy-Connection", ctx)
  • HTTP_REFERER - lookup_header("Referer", ctx)
  • HTTPS - flag ? "on" : "off"
  • HTTP_USER_AGENT - lookup_header("User-Agent", ctx)
  • IS_SUBREQ - (main ? "true" : "false")
  • PATH_INFO - path_info
  • QUERY_STRING - args
  • REMOTE_ADDR - connection->remote_ip
  • REMOTE_HOST
  • REMOTE_IDENT - ap_get_remote_logname(r)
  • REMOTE_NAME
  • REMOTE_PORT - r->connection->remote_addr->port
  • REMOTE_USER - user
  • REQUEST_FILENAME - same as script_filename
  • REQUEST_METHOD - method
  • REQUEST_URI - uri
  • SCRIPT_FILENAME - same as request_filename
  • SCRIPT_GROUP - unknown
  • SCRIPT_USER - unknown
  • SERVER_ADDR - connection->local_ip
  • SERVER_ADMIN - server->server_admin
  • SERVER_NAME - ap_get_server_name(r)
  • SERVER_PORT - ap_get_server_port(r)
  • SERVER_PROTOCOL - protocol
  • SERVER_SOFTWARE - ap_get_server_banner()
  • THE_REQUEST - the_request
  • TIME - %04d%02d%02d%02d%02d%02d
  • TIME_DAY
  • TIME_HOUR
  • TIME_MIN
  • TIME_MON
  • TIME_SEC
  • TIME_WDAY
  • TIME_YEAR

Special Rewrite Redirects

  1. "permanent" - HTTP_MOVED_PERMANENTLY
  2. "temp" - HTTP_MOVED_TEMPORARILY
  3. "seeother" - HTTP_SEE_OTHER
  4. digit

Protocols Recognized by Mod_Rewrite

  1. ajp:// - Apache JServ Protocol
  2. balancer:// - Apache Load Balancer
  3. ftp:// - File Transfer Protocol
  4. gopher:// - Gopher (protocol)
  5. http:// - Hypertext Transfer Protocol
  6. https:// - Hypertext Transfer Protocol Secure
  7. ldap:// - Lightweight Directory Access Protocol
  8. mailto: - The mailto URI scheme
  9. news: - News Protocol
  10. nntp:// - Network News Transfer Protocol

Mod_Rewrite Terms and Definitions

pattern
the RegExp pattern string
regexp
the RegExp pattern compilation
flags
Flags which control the substitution
forced_mimetype
forced MIME type of substitution
forced_handler
forced content handler of subst.
forced_responsecode
forced HTTP response status
env
added environment variables
cookie
added cookies
skip
number of next rules to skip
state
the RewriteEngine state
options
the RewriteOption state
rewritelogfile
the RewriteLog filename
rewritelogfp
the RewriteLog open filepointer
rewritelog: level
the RewriteLog level of verbosity
rewritemaps
the RewriteMap entries
rewriteconds
the RewriteCond entries (temp.)
rewriterules
the RewriteRule entries
directory
the directory where it applies
baseurl
the base-URL where it applies

REGEX Rewrite Guides

URL Rewriting Module

This module uses a rule-based rewriting engine (based on a regular-expression parser) to rewrite requested URLs on the fly.

It supports an unlimited number of additional rule conditions (which can operate on a lot of variables, even on HTTP headers) for granular matching and even external database lookups (either via plain text tables, DBM hash files or even external processes) for advanced URL substitution.

It operates on the full URLs (including the PATH_INFO part) both in per-server context (httpd.conf) and per-dir context (.htaccess) and even can generate QUERY_STRING parts on result. The rewriting result finally can lead to internal subprocessing, external request redirection or even to internal proxy throughput.

This module was originally written in April 1996 and gifted exclusively to the The Apache Software Foundation in July 1997 by

Ralf S. Engelschall

Mod_Rewrite Errors

  • Options FollowSymLinks or SymLinksIfOwnerMatch is off which implies that RewriteRule directive is forbidden: %s
  • RewriteCond: bad argument line
  • RewriteCond: NoCase option for non-regex pattern %s is not supported and will be ignored.
  • RewriteCond: cannot compile regular expression
  • RewriteRule: invalid HTTP response code %s for flag R
  • RewriteRule: unknown flag
  • RewriteRule: cannot compile regular expression
  • RewriteOptions: MaxRedirects option has been removed in favor of the global LimitInternalRecursion directive and will be ignored.
  • RewriteOptions: unknown option
  • RewriteMap: bad path to txt map:
  • RewriteMap: bad path to rnd map:
  • RewriteMap: bad map:
  • RewriteMap: bad path to dbm map:
  • RewriteMap: dbm type
  • RewriteMap: bad path to prg map:
  • RewriteMap: internal map not found:
  • RewriteMap: bad path to txt map:
  • RewriteMap: file for map not found:
  • Invalid RewriteLock path
  • RewriteBase: only valid in per-directory config files
  • RewriteBase: empty URL not allowed
  • RewriteBase: argument is not a valid URL
  • RewriteCond: bad flag delimiters
  • RewriteCond: unknown flag
  • RewriteLog and RewriteLogLevel are not supported by this build of mod_rewrite because it was compiled using the -DREWRITELOG_DISABLED compiler option. You have to recompile mod_rewrite WITHOUT this option in order to use the rewrite log.
  • mod_rewrite: Invalid RewriteLog path %s
  • mod_rewrite: could not open reliable pipe to RewriteLog filter %s
  • mod_rewrite: Invalid RewriteLog path %s
  • mod_rewrite: could not open RewriteLog file %s
  • mod_rewrite: Running external rewrite maps without defining a RewriteLock is DANGEROUS!
  • mod_rewrite: could not start RewriteMap program %s
  • mod_rewrite: cant access text RewriteMap file %s
  • mod_rewrite: cant access DBM RewriteMap file %s
  • mod_rewrite: Parent could not create RewriteLock file %s
  • mod_rewrite: Parent could not set permissions on RewriteLock check User and Group directives
  • mod_rewrite: could not create rewrite_log_lock
  • mod_rewrite: Could not set permissions on rewrite_log_lock check User and Group directives
  • mod_rewrite: could not init rewrite_mapr_lock_acquire in child
  • mod_rewrite: could not init rewrite log lock in child
  • mod_rewrite: could not init map cache in child
  • split uri=%s -> uri=%s, args=%s
  • reduce %s -> %s
  • strip matching prefix: %s -> %s
  • add subst prefix: %s -> %s
  • cant open RewriteMap file, see error log
  • cache lookup FAILED, forcing new map lookup
  • map lookup FAILED: map=%s[txt] key=%s
  • map lookup OK: map=%s[txt] key=%s -> val=%s
  • cache lookup OK: map=%s[txt] key=%s -> val=%s
  • randomly chosen the subvalue `%s
  • cant open DBM RewriteMap file, see error log
  • cache lookup FAILED, forcing new map lookup
  • map lookup FAILED: map=%s[dbm] key=%s
  • map lookup OK: map=%s[dbm] key=%s -> val=%s
  • cache lookup OK: map=%s[dbm] key=%s -> val=%s
  • map lookup FAILED: map=%s key=%s
  • map lookup OK: map=%s key=%s -> val=%s
  • map lookup FAILED: map=%s key=%s
  • map lookup OK: map=%s key=%s -> val=%s
  • lookahead: path=%s var=%s -> val=%s
  • lookahead: path=%s var=%s -> val=%s
  • RESULT=%s
  • escaping backreference %s to %s
  • setting env variable %s to %s
  • setting cookie %s, cookie
  • skipping already set cookie %s
  • RewriteCond URI (-U) check: path=%s -> status=%d
  • RewriteCond file (-F) check: path=%s -> file=%s status=%d
  • RewriteCond: input=%s pattern=%s%s%s%s => %s
  • remember %s to have MIME-type %s
  • remember %s to have Content-handler %s
  • add path info postfix: %s -> %s%s
  • strip per-dir prefix: %s -> %s
  • applying pattern %s to uri %s
  • rewrite %s -> %s, ctx->uri
  • forcing responsecode %d for %s
  • add per-dir prefix: %s -> %s%s
  • forcing proxy-throughput with %s
  • explicitly forcing redirect with %s
  • implicitly forcing redirect (rc=%d) with %s
  • forcing %s to get passed through to next API URI-to-filename handler
  • init rewrite engine with requested uri %s
  • go-ahead with proxy request %s [OK]
  • dconf->directory,trying to replace prefix %s with %s
  • escaping %s for redirect
  • redirect to %s [REDIRECT/%d]
  • initial URL equal rewritten URL: %s [IGNORING REWRITE]
  • dconf->directory, trying to replace prefix %s with %s
  • strip document_root prefix: %s -> %s
  • internal redirect with %s [INTERNAL REDIRECT]
  • pass through %s
  • force filename %s to have MIME-type %s
  • force filename %s to have the Content-handler %s,
  • init rewrite engine with requested uri %s
  • init rewrite engine with passed filename %s. Original uri = %s
  • uri already rewritten. Status %s, Uri %s, %s
  • attempt to make remote request from mod_rewrite without proxy enabled: %s
  • go-ahead with proxy request %s [OK]
  • escaping %s for redirect
  • redirect to %s [REDIRECT/%d]
  • local path result: %s
  • prefixing with document_root of %s FAILED
  • prefixed with document_root to %s
  • go-ahead with %s [OK]
  • pass through %s

Htaccess Apache cheatsheet Htaccess htaccess file mod_rewrite PHP rewrite Rewriting

 

 

Comments