This is a Canonical Question about Apache's mod_rewrite.
Changing a request URL or redirecting users to a different URL than the one they originally requested is done using mod_rewrite. This includes such things as:
- Changing HTTP to HTTPS (or the other way around)
- Changing a request to a page which no longer exist to a new replacement.
- Modifying a URL format (such as ?id=3433 to /id/3433 )
- Presenting a different page based on the browser, based on the referrer, based on anything possible under the moon and sun.
- Anything you want to mess around with URL
Everything You Ever Wanted to Know about Mod_Rewrite Rules but Were Afraid to Ask!
How can I become an expert at writing mod_rewrite rules?
- What is the fundamental format and structure of mod_rewrite rules?
- What form/flavor of regular expressions do I need to have a solid grasp of?
- What are the most common mistakes/pitfalls when writing rewrite rules?
- What is a good method for testing and verifying mod_rewrite rules?
- Are there SEO or performance implications of mod_rewrite rules I should be aware of?
- Are there common situations where mod_rewrite might seem like the right tool for the job but isn't?
- What are some common examples?
A place to test your rules
The htaccess tester web site is a great place to play around with your rules and test them. It even shows the debug output so you can see what matched and what did not.
Best Answer
mod_rewrite syntax order
mod_rewrite has some specific ordering rules that affect processing. Before anything gets done, the
RewriteEngine On
directive needs to be given as this turns on mod_rewrite processing. This should be before any other rewrite directives.RewriteCond
precedingRewriteRule
makes that ONE rule subject to the conditional. Any following RewriteRules will be processed as if they were not subject to conditionals.In this simple case, if the HTTP referrer is from serverfault.com, redirect blog requests to special serverfault pages (we're just that special). However, if the above block had an extra RewriteRule line:
All .jpg files would go to the special serverfault pages, not just the ones with a referrer indicating it came from here. This is clearly not the intent of the how these rules are written. It could be done with multiple RewriteCond rules:
But probably should be done with some trickier replacement syntax.
The more complex RewriteRule contains the conditionals for processing. The last parenthetical,
(html|jpg)
tells RewriteRule to match for eitherhtml
orjpg
, and to represent the matched string as $2 in the rewritten string. This is logically identical to the previous block, with two RewriteCond/RewriteRule pairs, it just does it on two lines instead of four.Multiple RewriteCond lines are implicitly ANDed, and can be explicitly ORed. To handle referrers from both ServerFault and Super User (explicit OR):
To serve ServerFault referred pages with Chrome browsers (implicit AND):
RewriteBase
is also order specific as it specifies how followingRewriteRule
directives handle their processing. It is very useful in .htaccess files. If used, it should be the first directive under "RewriteEngine on" in an .htaccess file. Take this example:This is telling mod_rewrite that this particular URL it is currently handling was arrived by way of http://example.com/blog/ instead of the physical directory path (/home/$Username/public_html/blog) and to treat it accordingly. Because of this, the
RewriteRule
considers it's string-start to be after the "/blog" in the URL. Here is the same thing written two different ways. One with RewriteBase, the other without:As you can see,
RewriteBase
allows rewrite rules to leverage the web-site path to content rather than the web-server, which can make them more intelligible to those who edit such files. Also, they can make the directives shorter, which has an aesthetic appeal.RewriteRule matching syntax
RewriteRule itself has a complex syntax for matching strings. I'll cover the flags (things like [PT]) in another section. Because Sysadmins learn by example more often than by reading a man-page I'll give examples and explain what they do.
The
.*
construct matches any single character (.
) zero or more times (*
). Enclosing it in parenthesis tells it to provide the string that was matched as the $1 variable.In this case, the first .* was NOT enclosed in parens so isn't provided to the rewritten string. This rule removes a directory level on the new blog-site. (/blog/2009/sample.html becomes /newblog/sample.html).
In this case, the first parenthesis expression sets up a matching group. This becomes $1, which is not needed and therefore not used in the rewritten string.
In this case, we use $1 in the rewritten string.
This rule uses a special bracket syntax that specifies a character range. [0-9] matches the numerals 0 through 9. This specific rule will handle years from 2000 to 2099.
This does the same thing as the previous rule, but the {2} portion tells it to match the previous character (a bracket expression in this case) two times.
This case will match any lower-case letter in the second matching expression, and do so for as many characters as it can. The
\.
construct tells it to treat the period as an actual period, not the special character it is in previous examples. It will break if the file-name has dashes in it, though.This traps file-names with dashes in them. However, as
-
is a special character in bracket expressions, it has to be the first character in the expression.This version traps any file name with letters, numbers or the
-
character in the file-name. This is how you specify multiple character sets in a bracket expression.RewriteRule flags
The flags on rewrite rules have a host of special meanings and usecases.
The flag is the
[L]
at the end of the above expression. Multiple flags can be used, separated by a comma. The linked documentation describes each one, but here they are anyway:L = Last. Stop processing RewriteRules once this one matches. Order counts!
C = Chain. Continue processing the next RewriteRule. If this rule doesn't match, then the next rule won't be executed. More on this later.
E = Set environmental variable. Apache has various environmental variables that can affect web-server behavior.
F = Forbidden. Returns a 403-Forbidden error if this rule matches.
G = Gone. Returns a 410-Gone error if this rule matches.
H = Handler. Forces the request to be handled as if it were the specified MIME-type.
N = Next. Forces the rule to start over again and re-match. BE CAREFUL! Loops can result.
NC = No case. Allows
jpg
to match both jpg and JPG.NE = No escape. Prevents the rewriting of special characters (. ? # & etc) into their hex-code equivalents.
NS = No subrequests. If you're using server-side-includes, this will prevent matches to the included files.
P = Proxy. Forces the rule to be handled by mod_proxy. Transparently provide content from other servers, because your web-server fetches it and re-serves it. This is a dangerous flag, as a poorly written one will turn your web-server into an open-proxy and That is Bad.
PT = Pass Through. Take into account Alias statements in RewriteRule matching.
QSA = QSAppend. When the original string contains a query (http://example.com/thing?asp=foo) append the original query string to the rewritten string. Normally it would be discarded. Important for dynamic content.
R = Redirect. Provide an HTTP redirect to the specified URL. Can also provide exact redirect code [R=303]. Very similar to
RedirectMatch
, which is faster and should be used when possible.S = Skip. Skip this rule.
T = Type. Specify the mime-type of the returned content. Very similar to the
AddType
directive.You know how I said that
RewriteCond
applies to one and only one rule? Well, you can get around that by chaining.Because the first RewriteRule has the Chain flag, the second rewrite-rule will execute when the first does, which is when the previous RewriteCond rule is matched. Handy if Apache regular-expressions make your brain hurt. However, the all-in-one-line method I point to in the first section is faster from an optimization point of view.
This can be made simpler through flags:
Also, some flags also apply to RewriteCond. Notably, NoCase.
Will match "ServerFault.com"