Apache mod_rewrite Introduction - Apache HTTP Server Version 2.4 (2024)

Available Languages: en |fr

This document supplements the mod_rewritereference documentation. Itdescribes the basic concepts necessary for use ofmod_rewrite. Other documents go into greater detail,but this doc should help the beginner get their feet wet.

  • Apache mod_rewrite Introduction - Apache HTTP Server Version 2.4 (2) Introduction
  • Apache mod_rewrite Introduction - Apache HTTP Server Version 2.4 (3) Regular Expressions
  • Apache mod_rewrite Introduction - Apache HTTP Server Version 2.4 (4) RewriteRule Basics
  • Apache mod_rewrite Introduction - Apache HTTP Server Version 2.4 (5) Rewrite Flags
  • Apache mod_rewrite Introduction - Apache HTTP Server Version 2.4 (6) Rewrite Conditions
  • Apache mod_rewrite Introduction - Apache HTTP Server Version 2.4 (7) Rewrite maps
  • Apache mod_rewrite Introduction - Apache HTTP Server Version 2.4 (8) .htaccess files

See also

  • Module documentation
  • Redirection and remapping
  • Controlling access
  • Virtual hosts
  • Proxying
  • Using RewriteMap
  • Advanced techniques
  • When not to use mod_rewrite
  • Comments

Introduction

The Apache module mod_rewrite is a very powerful andsophisticated module which provides a way to do URL manipulations. Withit, you can do nearly all types of URL rewriting that you may need. Itis, however, somewhat complex, and may be intimidating to the beginner.There is also a tendency to treat rewrite rules as magic incantation,using them without actually understanding what they do.

This document attempts to give sufficient background so that whatfollows is understood, rather than just copied blindly.

Remember that many common URL-manipulation tasks don't require thefull power and complexity of mod_rewrite. For simpletasks, see mod_alias and the documentationon mapping URLs to thefilesystem.

Finally, before proceeding, be sure to configuremod_rewrite's log level to one of the trace levels usingthe LogLevel directive. Although thiscan give an overwhelming amount of information, it is indispensable indebugging problems with mod_rewrite configuration, sinceit will tell you exactly how each rule is processed.

Regular Expressions

mod_rewrite uses the Perl CompatibleRegular Expression vocabulary. In this document, we do not attemptto provide a detailed reference to regular expressions. For that, werecommend the PCRE man pages, thePerl regularexpression man page, and MasteringRegular Expressions, by Jeffrey Friedl.

In this document, we attempt to provide enough of a regex vocabularyto get you started, without being overwhelming, in the hope thatRewriteRules will be scientificformulae, rather than magical incantations.

Regex vocabulary

The following are the minimal building blocks you will need, in orderto write regular expressions and RewriteRules. They certainly do notrepresent a complete regular expression vocabulary, but they are a goodplace to start, and should help you read basic regular expressions, aswell as write your own.

CharacterMeaningExample
. Matches any single character c.t will match cat, cot, cut, etc
+ Repeats the previous match one or more times a+ matches a, aa, aaa, etc
* Repeats the previous match zero or more times a* matches all the same things a+ matches, but will also match an empty string
? Makes the match optional colou?r will match color and colour
\ Escape the next character \. will match . (dot) and not any single character as explain above
^ Called an anchor, matches the beginning of the string ^a matches a string that begins with a
$ The other anchor, this matches the end of the string a$ matches a string that ends with a
( ) Groups several characters into a single unit, and captures a match for use in a backreference (ab)+ matches ababab - that is, the + applies to the group. For more on backreferences see below
[ ] A character class - matches one of the characters c[uoa]t matches cut, cot or cat
[^ ] Negative character class - matches any character not specified c[^/]t matches cat or c=t but not c/t

In mod_rewrite the ! character can beused before a regular expression to negate it. This is, a string willbe considered to have matched only if it does not match the rest ofthe expression.

Regex Back-Reference Availability

One important thing here has to be remembered: Whenever you use parentheses in Pattern or in one of the CondPattern, back-references are internally created which can be used with the strings $N and %N (see below). These are available for creating the Substitution parameter of a RewriteRule or the TestString parameter of a RewriteCond.

Captures in the RewriteRule patterns are (counterintuitively) available to all preceding RewriteCond directives, because the RewriteRule expression is evaluated before the individual conditions.

Figure 1 shows to which locations the back-references are transferred for expansion as well as illustrating the flow of the RewriteRule, RewriteCond matching. In the next chapters, we will be exploring how to use these back-references, so do not fret if it seems a bit alien to you at first.

Apache mod_rewrite Introduction - Apache HTTP Server Version 2.4 (11)
Figure 1: The back-reference flow through a rule.
In this example, a request for /test/1234 would be transformed into /admin.foo?page=test&id=1234&host=admin.example.com.

RewriteRule Basics

A RewriteRule consistsof three arguments separated by spaces. The arguments are

  1. Pattern: which incoming URLs should be affected by the rule;
  2. Substitution: where should the matching requests be sent;
  3. [flags]: options affecting the rewritten request.

The Pattern is a regular expression.It is initially (for the first rewrite rule or until a substitution occurs)matched against the URL-path of the incoming request (the part after thehostname but before any question mark indicating the beginning of a querystring) or, in per-directory context, against the request's path relativeto the directory for which the rule is defined. Once a substitution hasoccurred, the rules that follow are matched against the substitutedvalue.

Apache mod_rewrite Introduction - Apache HTTP Server Version 2.4 (13)
Figure 2: Syntax of the RewriteRule directive.

The Substitution can itself be one of three things:

1. A full filesystem path to a resource
RewriteRule "^/games" "/usr/local/games/web/puzzles.html"

This maps a request to an arbitrary location on your filesystem, muchlike the Alias directive.

2. A web-path to a resource
RewriteRule "^/games$" "/puzzles.html"

If DocumentRoot is setto /usr/local/apache2/htdocs, then this directive wouldmap requests for http://example.com/games to thepath /usr/local/apache2/htdocs/puzzles.html.

3. An absolute URL
RewriteRule "^/product/view$" "http://site2.example.com/seeproduct.html" [R]

This tells the client to make a new request for the specified URL.

Note that 1 and 2 have exactly the same syntax. The difference between them is that in the case of 1, the top level of the target path (i.e., /usr/) exists on the filesystem, where as in the case of 2, it does not. (i.e., there's no /bar/ as a root-level directory in the filesystem.)

The Substitution can alsocontain back-references to parts of the incoming URL-pathmatched by the Pattern. Consider the following:

RewriteRule "^/product/(.*)/view$" "/var/web/productdb/$1"

The variable $1 will be replaced with whatever textwas matched by the expression inside the parenthesis inthe Pattern. For example, a requestfor http://example.com/product/r14df/view will be mappedto the path /var/web/productdb/r14df.

If there is more than one expression in parenthesis, they areavailable in order in thevariables $1, $2, $3, and soon.

Rewrite Flags

The behavior of a RewriteRule can be modified by theapplication of one or more flags to the end of the rule. For example, thematching behavior of a rule can be made case-insensitive by theapplication of the [NC] flag:

RewriteRule "^puppy.html" "smalldog.html" [NC]

For more details on the available flags, their meanings, andexamples, see the Rewrite Flags document.

Rewrite Conditions

One or more RewriteConddirectives can be used to restrict the types of requests that will besubject to thefollowing RewriteRule. Thefirst argument is a variable describing a characteristic of therequest, the second argument is a regularexpression that must match the variable, and a third optionalargument is a list of flags that modify how the match is evaluated.

Apache mod_rewrite Introduction - Apache HTTP Server Version 2.4 (16)
Figure 3: Syntax of the RewriteCond directive

For example, to send all requests from a particular IP range to adifferent server, you could use:

RewriteCond "%{REMOTE_ADDR}" "^10\.2\."RewriteRule "(.*)" "http://intranet.example.com$1"

When more thanone RewriteCond isspecified, they must all match forthe RewriteRule to beapplied. For example, to deny requests that contain the word "hack" intheir query string, unless they also contain a cookie containingthe word "go", you could use:

RewriteCond "%{QUERY_STRING}" "hack"RewriteCond "%{HTTP_COOKIE}" !goRewriteRule "." "-" [F]

Notice that the exclamation mark specifies a negative match, so the rule is only applied if the cookie does not contain "go".

Matches in the regular expressions contained inthe RewriteConds can beused as part of the Substitution inthe RewriteRule using thevariables %1, %2, etc. For example, thiswill direct the request to a different directory depending on thehostname used to access the site:

RewriteCond "%{HTTP_HOST}" "(.*)"RewriteRule "^/(.*)" "/sites/%1/$1"

If the request was for http://example.com/foo/bar,then %1 would contain example.comand $1 would contain foo/bar.

Rewrite maps

The RewriteMap directiveprovides a way to call an external function, so to speak, to do yourrewriting for you. This is discussed in greater detail in the RewriteMap supplementary documentation.

.htaccess files

Rewriting is typically configured in the main server configurationsetting (outside any <Directory> section) orinside <VirtualHost>containers. This is the easiest way to do rewriting and isrecommended. It is possible, however, to do rewritinginside <Directory>sections or .htaccessfiles at the expense of some additional complexity. This techniqueis called per-directory rewrites.

The main difference with per-server rewrites is that the pathprefix of the directory containing the .htaccess file isstripped before matching inthe RewriteRule. In addition, the RewriteBase should be used to assure the request is properly mapped.

Apache mod_rewrite Introduction - Apache HTTP Server Version 2.4 (2024)

References

Top Articles
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated:

Views: 5800

Rating: 4.4 / 5 (55 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.