mod_rewrite

mod_rewrite modifies request path and querystring

It supports matching regular expressions and substitution with captured substrings as well as other placeholders.

If your rewrite target does not contain any question mark (?), then the querystring will not be altered.
If it does contain ? the querystring will be overwritten with the part after the ?. To append the original querystring, use %{request.query}.

IMPORTANT: rewrite only changes the url, not the physical filename that it got mapped to by docroot or alias actions. So you need your docroot and alias actions after the rewrite.
If you have conditional rewrites like if !phys.is_file { rewrite ... } you need docroot/alias both before (so it can check for the physical file) and after it (to build the new physical path).

rewrite (action)

modify request path and querystring

rewrite rule;
rule
a simple target string or one rule, mapping a regular expression to a target string, or a list of rules.
  • The target string is a pattern.
  • The regular expressions are used to match the request path (always starts with “/” and does not include the query string!)
  • If a list of rules is given, rewrite stops on the first match.
  • Replaces the query string iff the target string contains an ?

Example: rewrite always

setup {
	module_load "mod_rewrite";
}
rewrite "/new/path";

Example: rewrite if match

setup {
	module_load "mod_rewrite";
}
rewrite "regex" => "/new/path";

Example: rewrite on first match

setup {
	module_load "mod_rewrite";
}
rewrite ("regex1" => "/new/path1", ..., "regexN" => "/new/pathN");

Example: pretty urls

Note: you really should move the logic for such rewrites into your application, and just rewrite all pretty urls to your index.php without putting the actions into the querystring.

setup {
	module_load "mod_rewrite";
}

# bad: routing login in webserver config:
rewrite (
	"^/article/(\d+)/.*$" => "/article.php?id=$1",
	"^/download/(\d+)/(.*)$" => "/download.php?fileid=$1&filename=$2"
);
rewrite "^/user/(.+)$" => "/user.php?name=$1";

# good: handle it in the backend (easier to port the config)
rewrite "^/(article|download|user)(/|$)" => "/index.php";

rewrite_raw (action)

modify request path and querystring, matching and writing raw path

rewrite_raw rule;
rule
a simple target string or one rule, mapping a regular expression to a target string, or a list of rules.

Similar to rewrite, but matches the raw path (i.e. the path before URL decoding and sanitizing) and the result is decoded again.

rewrite writes the result to request.path and possibly request.query and uses URL encoding to generate request.raw_path from those.
rewrite_raw writes request.raw_path and decodes it into request.path and request.query; this means the query string is always overwritten.
In both cases request.path gets simplified afterwards.

rewrite.debug (option)

enable debug output

rewrite.debug value;
Default value: false