Mod_Rewrite: Flags, Rules, Conditions, Tutorial and Variables
Social BookMarking Links for RankingLabs.Com Search Engine Optimization Website. iGoogle, Digg, Del.icio.us, MyYahoo!
RankingLabs.Com. The Artistic Science of SEO. Solution Based Web Management.
Website SEO; The Artistic; The Scientific; Mod_Rewrite; BookMark; Contact. Graphical Navigation for Search Engine Optimization Topics.

Mod_Rewrite Services

Mod_Rewrite

Mod_Rewrite* is an Apache®** Web Server Module, which allows users to Rewrite, Redirect and otherwise manipulate URLs 'on the fly', based on a series of rules and (optionally) conditions, which are constructed of regular expressions (pattern matches), compared to information sent by a visitor, can include the Requested URI, Query String, HTTP Headers, Time Stamps, Environmental Variables, External Databases, etc. and can be applied in a server configuration file (httpd.conf) or in a directory access file (.htaccess).

* Mod_Rewrite developed by Ralf S. Engelschall.
** Apache is a Registered Trademark of The Apache Software Foundation.
Weblinks to Apache and the stated resources at the conclusion of this page.

Mod_Rewrite ‘How To’ & Tutorial Overview

Mod_Rewrite is a little complicated, but the basics when explained correctly are fairly easy to understand, assuming a basic background in website creation and regular expressions. This is just a ‘basics, to get things working’ page but it is more advanced than most, and much more advanced uses of Mod_Rewrite are possible. If this explanation is too advanced, consider starting with the six pages of ‘Beginner's Guides’ at ModRewrite.Com (linked at the conclusion of this web page), which are more basic, then return here when you are more comfortable.

Since most do not have access to the httpd.conf file all references are to the .htaccess file use of Mod_Rewrite, unless otherwise noted.

Definitions, Requirements, Settings

When attempting to understand Mod_Rewrite, there are some important things to remember:

If there is an error in the .htaccess or httpd.conf your website will not work.
It is always recommended to test rules on a testing server.

There is normally more than one possible rule (ruleset) which will work for a given situation.
Mod_Rewrite is Regular Expression based, meaning it is purely logical.
(Finding an effective and efficient solution is where skill becomes necessary.)

You, ‘The Person’, are Not ‘The Visitor’.
To Mod_Rewrite, the User Agent (a 'browser', a 'web robot' AKA 'web spider', etc.) and other Server Variables are the visitors. Visitors can be defined by IP Address (REMOTE_IP), by Internet Provider (REMOTE_HOST) and other server or environmental variables available. For the purposes of this page, the term visitor will refer to User Agent (HTTP_USER_AGENT).

Personal Security Note: None of the preceding server variables are personally identifiable by a Web Server, Weblog or Website. They define IP Addresses (which are assigned in ‘blocks’) and Providers of Service, but do not provide the location of the end user. EG A person in Vancouver, WA who has an Internet connection provided by a Portland, OR based company will usually have a Portland, OR IP Address, and will appear to a server or log files as a visitor from Portland, OR, not as a visitor from the location of their home in WA.
Mod_Rewrite Does Not 'Create' or 'Move' Anything.

Mod_Rewrite does change the basic server response for a given visitor request, when a specific pattern within the request is matched by a RewriteRule or RuleSet.

Mod_Rewrite is based on Rules and Conditions which can range from a Simple RewriteRule and regular expression to a Complex Series of Rules (RewriteRule), Condition(s) (RewriteCond), Flags, Environmental Variables, Back-References and Regular Expressions.

(A RuleSet=A group of rules & conditions. Examples Below.)

httpd.conf
Hyper Text Transfer Protocol Daemon Configuration. In English: A Web Server Configuration File.
.htaccess
Hyper Text (Transfer Protocol) Access File. In English: Controls access to files (on a per directory basis) on an Apache Web Server.
Mod_Rewrite Use.
Available for use on a per server basis via the httpd.conf, a per directory basis via the .htaccess, or a combination of the two where the server or all directories can be set to function with a single file, but ‘single directories’ can run off a unique file of their own. The easiest and most common use is in an .htaccess file in the root directory of a website.
(EG http://www.rankinglabs.com/.htaccess is the location of The Ranking Labs' rules. No, you can't see it.)
Mod_Rewrite File Size.
Depending on the efficiency of a file, and the server it is running on, size can range from a few lines to over 1000. There is no set limit to file size. If more than a few rules are present on a busy site, it is recommended to have the file professionally optimized. Inefficient or poorly written files can add a tremendous load to server processing, and can negatively impact page load time, even for pages which are not rewritten or redirected.
Canonical URLs.
Begin with http://domain.com/. Include the full path to a location.
Example: http://www.rankinglabs.com/the-path/to-a-file.html
On any website will always request http://www.rankinglabs.com/the-path/to-a-file.html
Server Relative URLs.
Will always begin with a preceding / and contain the full path to the location, from the Domain Name on.
Example: /the-path/to-a-file.html
On the website www.rankinglabs.com will always request http://www.rankinglabs.com/the-path/to-a-file.html
Directory Relative URLs.
Will not begin with preceding / and contain the path from the current location to the new location.
Example: the-path/to-a-file.html

From the root domain on www.rankinglabs.com (http://www.rankinglabs.com/):
the-path/to-a-file.html will request http://www.rankinglabs.com/the-path/to-a-file.html

From the directory /the-path/ on www.rankinglabs.com (http://www.rankinglabs.com/the-path/):
the-path/to-a-file.html will request http://www.rankinglabs.com/the-path/the-path/to-a-file.html
Redirect.
Sends the visitor to a different location, when a pattern is matched, and is externally visible in the address bar of the browser. For instance, when you type in an extension on a RankingLabs.Com URL the browser is redirected externally (visibly) to the a ‘matching’ location without an extension.

Redirects should always be Canonical URLs: http://www.rankinglabs.com/Mod_Rewrite.

Note: When redirecting URLs in a Search Engine Friendly manner it is important to use a single redirect.*

Example: When redirecting from http://rankinglabs.com/Mod_Rewrite.html to http://www.rankinglabs.com/Mod_Rewrite there should only be one redirect.

Not one from http://rankinglabs.com/Mod_Rewrite.html to http://www.rankinglabs.com/Mod_Rewrite.html.
Then another redirect from http://www.rankinglabs.com/Mod_Rewrite.html to http://www.rankinglabs.com/Mod_Rewrite.

* A single redirect is important, because it has been indicated ‘Link Weight’ will be passed through a single redirect by search engines, but will not be passed through multiple, or ‘stacked’ redirects.
Rewrite.
Provides information from a location other than the requested location transparently, and is not visible to the browser. EG RankingLabs.Com URLs do not have extensions, so requested URLs must be rewritten internally to the location of the file with the information presented on each page.

* Rewrites should usually (always) be server relative URLs: /Mod_Rewrite. Rewrite Example.
(Server Relative URLs are strongly recommended, unless you really know what you are doing, and/or like headaches, then feel free to use Directory Relative URLs.)

* If a Canonical URL is used in a rewrite, the browser will be redirected externally, even if a Redirect Flag [R=NUM] is not set. This will generate a '302' Redirect Status Code, which has caused issues with search engine indexing, and defeats the purpose of a Rewrite. When redirecting is necessary, using either a 301 ‘Permanent‘, 303 ‘See Other’, or 307 ‘Temporary’, which are the proper HTTP 1.1 Status Codes, is strongly recommended.
Requirements and Settings.

Mod_Rewrite must be loaded and active; is not provided by all hosting companies.

(Check with your host prior to use, or upload a PHP file with <?php phpinfo(); ?> to see modules available on your server.)

AllowOverride Must be Set to FileInfo (More Secure), or All (Not as Secure) in the httpd.conf.
AllowOverride FileInfo
Precedes RewriteEngine on if using the httpd.conf for Mod_Rewrite.

Is not available in .htaccess, and must be set (by hosting companies in most cases) in the httpd.conf if not already set to FileInfo or higher.
The Options Setting Must be FollowSymLinks, Either in the httpd.conf or .htaccess.
Options +FollowSymLinks
Precedes RewriteEngine on.

The easiest way to check this setting from the .htaccess file is to try a ruleset without setting the options.

If the redirect works, Options +FollowSymLinks is not necessary (already set in the httpd.conf file), and can cause a server error if set.

If a server error is generated, comment (Precede with #. EG # Options +FollowSymLinks) or delete the line.

Turning on Mod_Rewrite.
RewriteEngine on is required preceding any rules on a per file basis, but is only required once per file.
Rewrite Base.
RewriteBase /the-path/
Optionally used to define the default path for Rewrites.
Placed after RewriteEngine on, but preceding any RewriteRule(s).

Is essentially the same as a ‘base href’ header in HTML Code, which will apply to Directory Relative URLs, but not Server Relative URLs or Canonical URLs. In many cases it is easier (and recommended) to use the Server Relative Path (URL) with each rule to ensure the correct location is presented to the visitor when using rewrites.

Redirects should always be Canonical URLs (http://www.rankinglabs.com/the-path/to-a-file.html), so a base does not apply.
Rewrite Options.
RewriteOptions inherit

When multiple files are used on a per directory basis ‘deeper’ level .htaccess files can be set to ‘inherit’ options from parent files.
Placed after RewriteEngine on, but preceding any RewriteRule(s).

For Instance: If the main .htaccess file is in the ‘root’ (http://www.rankinglabs.com/.htaccess) and there is a secondary file in the directory ‘example’ (http://www.rankinglabs.com/example/.htaccess) the .htaccess file at /example/.htaccess can be set to ‘inherit’ the rules from the file in the ‘root’ .htaccess, by adding RewriteOptions inherit after RewriteEngine on, but preceding any RewriteRule(s).

(Setting MaxRedirects is also available. See the Apache 2.0 Mod_Rewrite Documentation for details.)

Rewrite Directives Not Covered.
RewriteLog | RewriteLogLevel | RewriteLock | RewriteMap
See the Apache 1.3 Mod_Rewrite Documentation.
Search Engine Friendly (SEF) URLs with Mod_Rewrite.
URLs without a Query_String (?'s or information after the QuestionMark, including SessionIDs) making a web page or website appear ‘static’ through the use of rewrites.
Simple Rule - Mod_Rewrite Rule & Regular Expression.
RewriteRule ^Mod_Rewrite\.html$ http://www.rankinglabs.com/Mod_Rewrite [R=301,L]
Simple Rule Explanation Below.
(Short) Complex RuleSet
Series of Mod_Rewrite Rules, Conditions, Variables, Back-References & Regular Expressions.
RewriteEngine on
# Code Base Provided by RankingLabs.Com #
RewriteRule \.htaccess - [F]
RewriteRule \.(txt|gif|jpe?g|css|ico)$ - [L]
RewriteCond %{HTTP_HOST} ^(www\.rankinglabs\.com)?$
RewriteCond %{THE_REQUEST} !index(\.html?)?
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ (/[^.?]*)+\ HTTP/1\.
RewriteRule .? - [S=4]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^.]*)
RewriteRule .? - [E=reqURI:%1,E=rED:yes]

RewriteCond %{ENV:reqURI} ^([^?]*)(\?|\ )
RewriteRule .? - [E=reqURI:%1]

RewriteCond %{ENV:reqURI} ^([^/]+/?)*index(\.html?)?$
RewriteRule .? - [E=reqURI:%1]

RewriteCond %{ENV:rED} ^yes$
RewriteRule .? http://www.rankinglabs.com/%{ENV:reqURI}? [R=301,L]

RewriteRule ([^.]+) /$1.html [L]

Complex RuleSet Explanation Below.

RewriteRule(s), RuleSets & Flags

Rules & RuleSets.
RewriteRule ^PATTERN-TO-MATCH$ ACTION-TO-TAKE-OR-LOCATION [Flag]
A Mod_Rewrite Rule always begins with: RewriteRule (Capitalization Matters.)
The ‘Left Side’ of the rule is always the comparison side.
The ‘Right Side’ of the rule is always the ‘action’ side.
Rule ‘Sides’ are always separated with a space.
A RewriteRule will always compare the requested location from the location of the rule forward in the directory structure.

Example: If http://www.rankinglabs.com/the-path/to-a-file.html is requested.
A rule in the httpd.conf file will attempt to match (compare) /the-path/to-a-file.html.

A rule in the root .htaccess file (http://www.rankinglabs.com/.htaccess) will attempt to match (compare) the-path/to-a-file.html.

A rule in the /the-path/ directory .htaccess file (http://www.rankinglabs.com/the-path/.htaccess) will attempt to match (compare) to-a-file.html.

Important Note: The preceding / is not compared in the .htaccess file(s), but is compared in the httpd.conf.

A ^ is the ‘Start Anchor’ of a Rule or Condition.

A $ is the ‘End Anchor‘ of a Rule or Condition.

As an example a Rule or RuleSet can be as simple as:
RewriteRule ^index\.html$ /index.php [L]

The above RewriteRule will Rewrite (transparently serve information from) index.php to index.html.

The ‘Left Side’ of the RewriteRule is the regular expression pattern to be matched.
If there is no match to the ‘Left Side’ of the RewriteRule, the ‘Right Side’ of the RewriteRule will have no effect on the request being made.

The ‘Left Side’ of a RewriteRule ends at a space.
(Rule ‘sides’ should always be single space separated, even if a $ is used.)

The ‘Right Side’ of the RewriteRule is the action required after a pattern is matched, begins after the space, and should always end with a ‘Flag’, which is defined by brackets[]. (Usually a minimum flag of [L], for ‘Last’, unless you know it is not necessary, is required.)

When a Condition (RewriteCond) is used, it is processed between a match on the ‘Left Side’ of the RewriteRule, and the action on the right. If the ‘Left Side’ of the RewriteRule and all conditions do not match, the ‘Right Side’ of the RewriteRule will not have an effect on the request.

RewriteRule Order.
Critical, not only to matching patterns correctly, but for efficiency. Single URL RewriteRules should come before any more ambiguous ‘Pattern Matches’. Pattern matches should be ordered from top to bottom, most specific to least specific.
RewriteRule Back-Reference
Grouping designated with () on the ‘Left-Side’ of a RewriteRule. Recalled through the use of $NUM on the ‘Right-Side’ of a RewriteRule, or $NUM on either the ‘Left-Side’ or ‘Right-Side’ of a condition.

RewriteRule ^(.) $1

The above would store the first character of any request as $1.
To determine the NUM for the $NUM count left parenthesis from left to right.
RewriteRule Flags
Allow for the setting of ‘instructions’, headings and variables within Mod_Rewrite, which are either used internally, or sent externally in the form of a Server Header to a visitor.
C - Chain
Indicates internally to Mod_Rewrite a RewriteRule should be ‘Chained’ to the next RewriteRule in succession. The succeeding RewriteRule will not be processed if the ‘Left Side’ of a RewriteRule or any RewriteCond fail to match a request. Can be used for more than one successive RewriteRule, but if any RewriteRule in the Chain fails, the remainder of the Chain will be skipped.
E - Environmental Variable
Allows the setting of an internal environmental variable. Format is [E=VARname:VARvalue].
See Setting Environmental Variables for details.
F - Forbidden
Serves an HTTP 1.x 403 Forbidden header. Denies the requesting user agent (visitor) access to a requested resource.
L (last) Flag is not required.
G - 410 Gone

Serves an HTTP 1.1 410 Gone header. A 410 Gone header differs from a 404 Not Found, in that a 410 Gone is only served deliberately, while a 404 Not Found is served by default.
L (last) Flag is not required.

410 Gone=The resource is permanently, purposely, intentionally removed.
404 Not Found=The resource is Not Found (at this time), but does not indicate a permanent or intentional situation.

L - Last
Indicates internally to Mod_Rewrite, 'This is the Last RewriteRule to process prior to taking action. (EG Redirect the Visitor)'. Failure to indicate Last when using multiple RewriteRules can cause unexpected results, and therefore should always be used unless you know it is not necessary.
N - Next (Round)
Indicates internally to Mod_Rewrite to reprocess the requested location again from the beginning of the file.
NC - No Case
Internally changes a comparison from Case Sensitive (default) to Case Insensitive.
Examples:
RewriteRule ^Mod_Rewrite$ - [L] will match exactly Mod_Rewrite.
RewriteRule ^Mod_Rewrite$ - [NC,L] will match Mod_Rewrite, MOD_REWRITE, mOd_ReWriTe and so on.
NE - No Escape
Keeps URLs from being ‘escaped’ or ‘encoded’ to allow for special characters in Rewritten and Redirected URLs.
NS - No SubRequest
Internally removes sub-requests from being processed by the RewriteRule, even if the sub-request pattern matches the ‘Left Side’ of the RewriteRule and all RewriteConds.
P - Proxy
Serves the ‘Right Side‘ (location in this case) of the RewriteRule as a proxy request, meaning the location is requested remotely (usually), but served as if it is a local resource.
L (last) Flag is not required.
PT - Pass Through
Allows a ‘Mod_Rewrite Manipulated’ (Rewritten or Redirected) URL to be passed to the next type of handler.
Example: If Mod_Rewrite loads first, then Mod_Alias loads URLs will be processed by Mod_Rewrite, and usually served, prior to being processed by Mod_Alias. To use both prior to sending the reconstructed URL to a visitor, use the PT flag, and Mod_Rewrite will pass the URL through to Mod_Proxy, rather than sending the URL to the visitor. (Load order of modules is dependent on a web server's configuration. Usually set by the host.)
QSA - Query String Append
Appends a Query_String to a URL. Used when it is necessary to add information to an existing Query_String, while rewriting or redirecting a URL.
R - Redirect

Serves an HTTP 1.x Redirect. Redirect code should be defined. Will externally (visible in the address bar of a browser) redirect the visitor to the location on the ‘Right Side’ of a RewriteRule.

[R=301] 301 Permanent Redirect - HTTP 1.0 & HTTP 1.1 (Recommended, unless a resource will be returned to the location.)
[R=302] 302 Found - HTTP 1.0 & HTTP 1.1 *
[R=303] 303 See Other - HTTP 1.1
[R=307] 307 Temporary Redirect - HTTP 1.1
* A 302 is usually handled similar to a 303 ‘See Other’. See HTTP 1.1 Status Codes for details of redirect handling.
It is always advisable to check with search engines individually to ensure a specific code is handled in the expected manner, since some adjust handling of certain types of redirects in a way they feel is more beneficial to their visitors.

S - Skip
Internally indicates the next N number of rules should be skipped if the current RewriteRule and all RewriteConds are matched. Format is [S=NUM] EG: [S=5] will skip the next 5 rules.
T - Type

Forces an internal processing handler on requests matching the ‘Left Side’ of a RewriteRule and all RewriteConds.
Example: Can be used to force all .html files to be parsed as .php, similar to AddType.

RewriteRule \.html$ - [T=application/x-httpd-php,L]
Condition(s) & Predefined Server Variables

When using conditions remember:
A Condition must have a Rule, but a RewriteRule does not need a condition.
(IOW A Condition cannot be used by itself, but a rule can.)

The more variables present, there more chances there are to lose efficiency.

Rewrite Condition.
RewriteCond comparison-VALUE PATTERN-TO-MATCH [Flag]
RewriteCond %{SERVER_VARIABLE_NAME} PATTERN-TO-MATCH [NC]

Precedes a RewriteRule, and only has effect on the single RewriteRule it precedes.
Also, only has an effect if the ‘Left Side’ RewriteRule pattern in matched.
Multiple Conditions per RewriteRule are possible.
Multiple RewriteRules per condition without ‘Chaining’ RewriteRules are not.
(Effective ‘Chaining’ is more advanced than the scope of this page.)
Condition Processing Order.
‘Left Side’ of the RewriteRule.
Condition(s). (Top to bottom for multiple conditions.)
‘Right Side’ of the RewriteRule. (If all conditions are met.)
Average Conditions.
Most begin with a predefined %{SERVER_VARIABLE} to be compared, which is not available to a RewriteRule, or supplements the matching pattern of a RewriteRule to provide a more specific ‘match’.
Server Variables.
Predefined variables for use with Mod_Rewrite. The most widely used and/or necessary are:
HTTP_USER_AGENT, HTTP_REFERER, HTTP_HOST, QUERY_STRING, REQUEST_URI, THE_REQUEST.
HTTP_USER_AGENT
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)
Contains the name and usually version, etc. of a User Agent (AKA Visitor, Browser, Web Spider).
HTTP_REFERER
http://www.rankinglabs.com/Mod_Rewrite/page.php?var=val
Full URL (including http://) of the resource a visitor requested the new location from.

(IOW The full Canonical URL (web address) of where a visitor ‘came from’. Usually by clicking a link.)

Example: A visitor clicking a link on the home page of RankingLabs.Com to the Mod_Rewrite web page will result in the referrer being http://www.rankinglabs.com/.

QuestionMark and value are present if there was a Query_String on the referring web page or location.
%{HTTP_REFERER} Misspelled with 1 R is correct.
HTTP_HOST
www.rankinglabs.com OR rankinglabs.com OR sub.sub.rankinglabs.com
Domain name (and any sub.domain if present) only of the current website.

This variable is not defined by HTTP/1.0 User Agents (AKA Visitors, Browsers, Web Spiders), but is sent by most currently in use.
QUERY_STRING
Information following the QuestionMark in a URL.

The value of the QUERY_STRING server variable in Mod_Rewrite is the information following the QuestionMark, and does not include the QuestionMark itself.

Example: If http://www.rankinglabs.com/Mod_Rewrite?var=val is requested the ‘value’ of %{QUERY_STRING} will be var=val.

No Preceding QuestionMark is present for matching.
The QuestionMark ‘says’ Query_String to a web server, and is usually ‘transparent’ in matching.

The information following a QuestionMark is technically not part of the requested location, but rather information passed to the location. The QuestionMark itself allows the server and 'receiving' web page to know there is information being passed. The QuestionMark is invisible to Mod_Rewrite for matching purposes, except for %{THE_REQUEST}, in which it is present.

Example: index.php?var=1 has a Requested Location of index.php, with a Value of var=1 passed to the location index.php.
REQUEST_URI
/Mod_Rewrite/page.ext
Full Server Relative URL Path of the requested location.
THE_REQUEST
METHOD /full-ServerRelative-path/page.ext?Var=Query_String HTTP/vNUM.vNUM
Example 1: %{THE_REQUEST} GET /some-dir/some-subDIR/page.html HTTP/1.1
Example 2: %{THE_REQUEST} GET /dir/index.php\?var=val HTTP/1.1
Example 3: %{THE_REQUEST} POST /search.php HTTP/1.1

METHOD is usually 1 of: CONNECT DELETE GET HEAD OPTIONS POST PUT PROPFIND TRACE
Available for original requests only. (GET & POST are most common. Not all methods are listed.)
See RFC 2616 Method Definitions & RFC 2518 HTTP Extensions for more details and request types.

A QuestionMark is present if a Query_String is included with the requested URL.

If a request is internally redirected it will not qualify for THE_REQUEST after the redirect is issued. In Other Words: The URL (location) request must be issued by the visitor.

Think (in most cases) ‘visible in the browser address bar’ = Original Request = THE_REQUEST can be used.
REMOTE_IP
255.255.255.255
IP (Internet Protocol) Address of the Visitor in the format of NUM.NUM.NUM.NUM.
Range of each is 0-255.
Some IP Addresses are 'reserved'.

Reserved IP Address Example: 127.0.0.1 is a 'Loop Back', which will ‘request’ the IP Address it is issued from, and can be used for testing when a web server is installed on a home computer, etc.
REMOTE_HOST

Name of Internet Provider a visitor is accessing a website through.
Requires HostnameLookups on which will add a delay to the processing of requests, because a 'Reverse Lookup' for the name associated with an IP Address must be issued to the DNS system for each request to find the name of a host. If a name is not present, only an IP Address will be returned.

Variable Formatting
Calling Server Variables, Setting Environmental Variables, Calling Environmental Variables.
%{VARIABLE_NAME}
Pre-defined Server Variables: Begin with percent, then opening ‘Curly Brace’, ALLCAPS_VARIABLE_NAME, closing ‘Curly Brace’.

Example: %{REQUEST_URI} is the proper format to ‘call’ (or use) the REQUEST_URI server variable.
(Spaces should be replaced with Underscores.)
Setting Environmental Variables: [E=name:VALUE]
Should be set as a ‘Flag’ on the ‘Right Side‘ of a RewriteRule.
The E ‘Flag’ indicates an environmental variable is to be set.
The equal sign signifies the beginning of the name.
The colon defines the end of the name and the beginning of the value.
Calling Environmental Variables: %{ENV:name}
Begin with percent, then opening ‘Curly Brace’, ENV, colon, Variable Name, closing ‘Curly Brace’.
(Spaces should be replaced with Underscores.)
Example Rules & RuleSets Explained
Simple Rule:
RewriteRule ^Mod_Rewrite\.html$ http://www.rankinglabs.com/Mod_Rewrite [R=301,L]
Simple Rule Explained - Mod_Rewrite Rule & Regular Expression:
RewriteRule ^Mod_Rewrite\.html$ http://www.rankinglabs.com/Mod_Rewrite [R=301,L]
RewriteRule (Left Side): If a visitor request is Mod_Rewrite.html.*
RewriteRule (Right Side): Send them to http://www.rankinglabs.com/Mod_Rewrite with no extension.
Flag 1 [R=301]: Set the Redirect Status to 301, ‘Permanent’, Redirect the visitor.**
Flag 2 [L]: This is the Last RewriteRule to attempt to match, ‘stop processing’.**

* The ^ denotes the beginning of the pattern, and the $ designates the end, so the requested location must be *exactly* Mod_Rewrite.html. The pattern would not match Apache/Mod_Rewrite.html.

To match all requests ending in Mod_Rewrite.html the preceding ^ can be omitted, with the $ in place.
(RewriteRule Mod_Rewrite\.html$).

To match all requests beginning with Mod_Rewrite.html, the ^ should be in place, with the $ omitted.
(RewriteRule ^Mod_Rewrite\.html).

To match all requests for Mod_Rewrite.html anywhere in the requested URL*** both the ^ and the $ should be omitted.
(RewriteRule Mod_Rewrite\.html).


** Multiple Flags should be comma separated within one set of brackets. Flags are bracketed individually for explanations only.

*** This matching does not include Mod_Rewrite.html following a ? (Query_String) in the request. To match a pattern in a Query_String, a condition with %{QUERY_STRING} must be used, since a Query_String is passed as information to the location, not as part of the location itself. EG index.php is a location, so index.php?var=Query_String requests the location of index.php, and passes the information var=Query_String to the location requested, which is index.php.
Complex RuleSet.
Below or something similar is used to:
Redirect a domain to www, rather than non-www.
Redirect requests for /directory/index.ext to /directory/.
Redirect to ‘Extensionless’.
Redirect to ‘Query_Stringless’.
Use a single redirect to accomplish any or all of the four possible redirects.
NOTE: Depending on server configuration, file type and other variables, minor edits to the code base may be necessary for proper code function.
RewriteEngine on
# Code Base Provided by RankingLabs.Com #
RewriteRule \.htaccess - [F]
RewriteRule \.(txt|gif|jpe?g|css|ico)$ - [L]
RewriteCond %{HTTP_HOST} ^(www\.rankinglabs\.com)?$
RewriteCond %{THE_REQUEST} !index(\.html?)?
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ (/[^.?]*)+\ HTTP/1\.
RewriteRule .? - [S=4]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^.]*)
RewriteRule .? - [E=reqURI:%1,E=rED:yes]

RewriteCond %{ENV:reqURI} ^([^?]*)(\?|\ )
RewriteRule .? - [E=reqURI:%1]

RewriteCond %{ENV:reqURI} ^([^/]+/?)*index(\.html?)?$
RewriteRule .? - [E=reqURI:%1]

RewriteCond %{ENV:rED} ^yes$
RewriteRule .? http://www.rankinglabs.com/%{ENV:reqURI}? [R=301,L]

RewriteRule ([^.]+) /$1.html [L]

* If you decide to use the above as a copy & paste starting point to make your website extensionless, make sure you place the code after RewriteEngine on and prior to any other RewriteRules, change occurrences of www.rankinglabs.com to yoursub.yoursite.tld, change \.html? to \.yourextension and $1.html to $1.yourextension, respectively (if necessary), and please leave the attribution** line (# Code Base Provided by RankingLabs.Com #) on the top of the ruleset in either the .htaccess or httpd.conf file.

** No, RankingLabs.Com will probably not ask to see your .htaccess or httpd.conf to check for attribution, but it is ‘cool’ to attribute RankingLabs.Com for code from RankingLabs.Com.


*** If you currently use Query_String URLs, please, do not use this code, unless you know how to adjust your URLs to work without Query_Strings, and know how to pass the Query_String information from the URLs to the page(s) (EG index.php) your website runs on.
Complex RuleSet Explained
Series of Mod_Rewrite Rules, Conditions, Variables, Back-References & Regular Expressions
:

* Code efficiency note: There is really no need for some of the ‘double checks’.
For example, the condition on the 2nd to last RewriteRule to check for a match of the environmental variable rED is unnecessary, but in an effort to make the tutorial more comprehensive an ‘efficient’, but not ‘most efficient’ ruleset was used.

RewriteRule \.htaccess - [F]
RewriteRule (Left Side): If a visitor request contains .htaccess.
RewriteRule (Right Side): There is no Redirect or Rewrite (-).
Flag 1 [F]: Access is ‘Forbidden’. (Last is not necessary.)

RewriteRule \.(txt|gif|jpe?g|css|ico)$ - [L]
RewriteRule (Left Side): If a visitor request ends in .txt, .gif, .jpg, .jpeg, .css, .ico.*
RewriteRule (Right Side): There is no Redirect or Rewrite (-).
Flag 1 [L]: This is the Last RewriteRule ‘stop processing’.

* In Mod_Rewrite an ‘Escaped’ \. , or bracketed [.] Dot or Period is a ‘Literal Dot or Period ’ in a visitor request, but an ‘Unescaped’ .(dot) Period in a Rule, Condition, Regular Expression is ‘Any character, which is not the end of a line.’.

RewriteCond %{HTTP_HOST} ^(www\.rankinglabs\.com)?$
RewriteCond %{THE_REQUEST} !index(\.html?)?
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ (/[^.?]*)+\ HTTP/
RewriteRule .? - [S=4]

RewriteRule (Left Side): If a visitor request contains 0 or 1 characters anywhere in the string process the conditions.*
RewriteCond 1: If the requested domain is www.rankinglabs.com or empty.**
RewriteCond 2: If the originally requested location does not contain index, optionally followed by .htm or .html.***
RewriteCond 3: If the originally requested location does not contain a .(dot) or a ?(QuestionMark).**
RewriteRule (Right Side): There is no Redirect or Rewrite (-).
Flag 1 [S=4]:
Skip the next 4 rules.

* The preceding / is not present to RewriteRules in the .htaccess file, so a request for http://www.rankinglabs.com/ is ‘seen’ as empty by Mod_Rewrite, and a request for /Mod_Rewrite is ‘seen’ as Mod_Rewrite, making it necessary to check for 0 or 1 character in order to match all requests. In the httpd.conf, since the preceding / is present, the ? can be omitted to match all requests.

** In Mod_Rewrite an ‘Escaped’ \?, or bracketed [?] QuestionMark is a ‘Literal QuestionMark’ in a visitor request, but an ‘Unescaped’ ? (QuestionMark) in a Rule or Condition Regular Expression means ‘0 to 1 of the preceding character or group of characters.’.

*** In Mod_Rewrite an ! may be placed at the beginning of the ‘Left-Side’ of a RewriteRule, or at the beginning of the ‘Right-Side’ of a RewriteCond to indicate the entire match should be a negative match.
In Other Words: An ! says, ‘The Requested Location is not… ’.
(An ! cannot be added in the middle of a pattern to switch to a negative match, EG match-to-here!don't-match-here will not work.)

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^.]*)
RewriteRule .? - [E=reqURI:%1,E=rED:yes,NS]

RewriteRule (Left Side): If the visitor request did not skip the next 4 rules, match the same pattern: 0 or 1 character anywhere in the string.
RewriteCond 1: Match the pattern of the original request to store for Back-Reference () from the character following the / to the .(dot) ([^.]*) if present, otherwise, store the entire request from the character following the / for Back-Reference.*
RewriteRule (Right Side): There is no Redirect or Rewrite (-).
Flag 1 [E=reqURI:%1]: Set an environmental variable reqURI via Back-Reference to the condition (%1).
Flag 2 [E=rED:yes]: Set an environmental variable rED to ‘yes’.
Flag 3 [NS]: Do not consider sub-requests a ‘match’.**

* Unlike RewriteRules the preceding / on a request is visible to certain predefined variables in the .htaccess file, including %{REQUEST_URI} and %{THE_REQUEST}.

** NS is not included in the example, because it is optional.

RewriteCond %{ENV:reqURI} ^([^?]*)(\?|\ )
RewriteRule .? - [E=reqURI:%1]

RewriteRule (Left Side): Match 0 or 1 characters anywhere in the string.
RewriteCond 1: If the environmental variable reqURI contains a ? (Query_String) or a space (\ ), store everything preceding the ? (Query_String) or space for Back-Reference.
RewriteRule (Right Side): There is no Redirect or Rewrite (-).
Flag 1 [E=reqURI:%1]: Set the reqURI variable, to everything preceding either the space or ?. (The remainder will be dropped.)

RewriteCond %{ENV:reqURI} ^([^/]+/?)*index(\.html?)?$
RewriteRule .? - [E=reqURI:%1]

RewriteRule (Left Side): Match 0 or 1 characters anywhere in the string.
RewriteCond 1: If the environmental variable reqURI contains the word ‘index’, optionally followed by .htm or .html ((\.html?)?), store everything preceding index for BackReference.
RewriteRule (Right Side): There is no Redirect or Rewrite (-).
Flag 1 [E=reqURI:%1]: Set the reqURI variable, to everything preceding index.

RewriteCond %{ENV:rED} ^yes$
RewriteRule .? http://www.rankinglabs.com/%{ENV:reqURI}? [R=301,L]

RewriteRule (Left Side): Match 0 or 1 characters anywhere in the string.
RewriteCond 1: Double check to make sure the environmental variable rED is ‘yes’ indicating the first RewriteRule was a match, and there should be a redirect.
RewriteRule (Right Side): Set the new location to: http://www.rankinglabs.com/value-of-reqURI?*
Flag 1 [R=301]: Set the Redirect Status to 301, ‘Permanent’.
Flag 2 [L]: This is the Last RewriteRule to attempt to match, ‘stop processing’. Redirect the visitor.

* A QuestionMark followed by ‘nothing’ on the ‘Right Side’ of the RewriteRule will append a blank Query_String to the URL.
(Remove the QuestionMark from a URL.)

RewriteRule ([^.]+) /$1.html [L]
RewriteRule (Left Side): Match 1 or more characters anywhere in the string.
RewriteRule (Right Side): Serve the information from /value-of-anything-requested-before-a-dot.html
Flag 1 [L]: Stop Processing for this ruleset.

Other Mod_Rewrite Resources

ModRewrite Tutorials
(ModRewrite.Com)

Rewriting Guide
(Apache.Org)

Apache
(Apache.Org)

Mod_Rewrite v1.3
(Apache.Org)

ModRewrite Tutorials
(WebmasterWorld.Com)

Copyright RankingLabs.Com All Rights Reserved.

RL-MRW-v01

Mod_Rewrite Website SEO Services Bookmark Mod_Rewrite: RankingLabs.Com Contact RankingLabs.com SEO, The Science SEO, The Art RankingLabs.Com Mod_Rewrite Website SEO Services Bookmark Mod_Rewrite: RankingLabs.Com Contact RankingLabs.com SEO, The Science RankingLabs.Com SEO, The Art BookMark to Del.icio.us BookMark to iGoogle BookMark to Digg.com BookMark to Yahoo! BookMark to Sprul.net BookMark to BlinkList.com Bookmark to StumbleUpon