Friday, March 10, 2017

Apache mod_rewrite module tutorial

<IfModule mod_rewrite.c>
RewriteEngine On # Turn on the rewriting engine

</IfModule>


Rewrite rules can be preceded by one or more rewrite conditions.
Eg :
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wordpress/index.php [L]


. (any character)
* (zero of more of the preceding)
+ (one or more of the preceding)
{} (minimum to maximum quantifier)
? (ungreedy modifier)
! (at start of string means "negative pattern")
^ (start of string, or "negative" if at the start of a range)
$ (end of string)
[] (match any of contents)
- (range if used between square brackets)
() (group, backreferenced group)
| (alternative, or)
\ (the escape character itself)

Flags :

C (chained with next rule)
CO=cookie (set specified cookie)
E=var:value (set environment variable var to value)
F (forbidden - sends a 403 header to the user)
G (gone - no longer exists)
H=handler (set handler)
L (last - stop processing rules)
N (next - continue processing rules)
NC (case insensitive)
NE (do not escape special URL characters in output)
NS (ignore this rule if the request is a subrequest)
P (proxy - i.e., apache should grab the remote content specified in the substitution section and return it)
PT (pass through - use when processing URLs with additional handlers, e.g., mod_alias)
R (temporary redirect to new URL)
R=301 (permanent redirect to new URL)
QSA (append query string from request to substituted URL)
S=x (skip next x rules)
T=mime-type (force specified mime type)

To redirect all requests missing "www" (yes www):
RewriteCond %{HTTP_HOST} ^domain\.com [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]