Cari di Apache 
    Apache Server Manual
Daftar Isi
(Sebelumnya) IntroductionTechnical details (Berikutnya)

Apache mod_rewrite Flags

This document discusses the flags which are available to theRewriteRule directive,providing detailed explanations and examples. This is not necessarilya comprehensive list of all flags available, so be sure to alsoconsult the reference documentation.

top

Introduction

RewriteRules can havetheir behavior modified by one or more flags. Flags are included insquare brackets at the end of the rule, and multiple flags are separatedby commas.

RewriteRule pattern target [Flag1,Flag2,Flag3]

The flags all have a short form, such as CO, as well asa longer form, such as cookie. Some flags take one or morearguments. Flags are not case sensitive.

top

The flags

Each flag has a long and short form. While it is most common to usethe short form, it is recommended that you familiarize yourself with thelong form, so that you remember what each flag is supposed to do.

Presented here are each of the available flags, along with an exampleof how you might use them.

C|chain

The [C] or [chain] flag indicates that the RewriteRule is chained to the nextrule. That is, if the rule matches, then it is processed as usual andcontrol moves on to the next rule. However, if it does not match, thenthe next rule, and any other rules that are chained together, will beskipped.

CO|cookie

The [CO], or [cookie] flag, allows you to set a cookie when aparticular RewriteRulematches. The argument consists of three required fields and two optionalfields.

You must declare a name and value for the cookie to be set, and thedomain for which you wish the cookie to be valid. You may optionally setthe lifetime of the cookie, and the path for which it should bereturned.

By default, the lifetime of the cookie is the current browsersession.

By default, the path for which the cookie will be valid is "/" - thatis, the entire website.

Several examples are offered here:

RewriteEngine On
RewriteRule ^/index.html - [CO=frontdoor:yes:.apache.org:1440:/]

This rule doesn't rewrite the request (the "-" rewrite target tellsmod_rewrite to pass the request through unchanged) but sets a cookiecalled 'frontdoor' to a value of 'yes'. The cookie is valid for any hostin the .apache.org domain. It will be set to expire in 1440minutes (24 hours) and will be returned for all URIs.

E|env

With the [E], or [env] flag, you can set the value of an environmentvariable. Note that some environment variables may be set after the ruleis run, thus unsetting what you have set. See theEnvironment Variables document for more details on how Environmentvariables work.

The following example sets an evironment variable called 'image' to avalue of '1' if the requested URI is an image file. Then, thatenvironment variable is used to exclude those requests from the accesslog.

RewriteRule .(png|gif|jpg) - [E=image:1]
CustomLog logs/access_log combined env=!image

Note that this same effect can be obtained using SetEnvIf. This technique is offered asan example, not as a recommendation.

F|forbidden

Using the [F] flag causes Apache to return a 403 Forbidden statuscode to the client. While the same behavior can be accomplished usingthe Deny directive, this allows more flexibility in assigning a Forbidden status.

The following rule will forbid .exe files from beingdownloaded from your server.

RewriteRule .exe - [F]

This example uses the "-" syntax for the rewrite target, which meansthat the requested URI is not modified. There's no reason to rewrite toanother URI, if you're going to forbid the request.

G|gone

The [G] flag forces Apache to return a 410 Gone status with theresponse. This indicates that a resource used to be available, but is nolonger available.

As with the [F] flag, you will typically use the "-" syntax for therewrite target when using the [G] flag:

RewriteRule oldproduct - [G,NC]

H|handler

Forces the resulting request to be handled with the specifiedhandler. For example, one might use this to force all files without afile extension to be parsed by the php handler:

RewriteRule !. - [H=application/x-httpd-php]

The regular expression above - !. - will match any requestthat does not contain the literal . character.

L|last

The [L] flag causes mod_rewrite to stop processingthe rule set. In most contexts, this means that if the rule matches, nofurther rules will be processed.

If you are using RewriteRule in either.htaccess files or in <Directory> sections,it is important to have some understanding of how the rules areprocessed. The simplified form of this is that once the rules have beenprocessed, the rewritten request is handed back to the URL parsingengine to do what it may with it. It is possible that as the rewrittenrequest is handled, the .htaccess file or <Directory> sectionmay be encountered again, and thus the ruleset may be run again from thestart. Most commonly this will happen if one of the rules causes aredirect - either internal or external - causing the request process tostart over.

It is therefore important, if you are using RewriteRule directives in one of thesecontext that you take explicit steps to avoid rules looping, and notcount solely on the [L] flag to terminate execution of a series ofrules, as shown below.

The example given here will rewrite any request toindex.php, giving the original request as a query stringargument to index.php, however, if the request is alreadyfor index.php, this rule will be skipped.

RewriteCond %{REQUEST_URI} !index.php
RewriteRule ^(.*) index.php?req=$1 [L]

N|next

The [N] flag causes the ruleset to start over again from the top. Usewith extreme caution, as it may result in loop.

The [Next] flag could be used, for example, if you wished to replace acertain string or letter repeatedly in a request. The example shown herewill replace A with B everywhere in a request, and will continue doingso until there are no more As to be replaced.

RewriteRule (.*)A(.*) $1B$2 [N]

You can think of this as a while loop: While thispattern still matches, perform this substitution.

NC|nocase

Use of the [NC] flag causes the RewriteRule to be matched in acase-insensitive manner. That is, it doesn't care whether letters appearas upper-case or lower-case in the matched URI.

In the example below, any request for an image file will be proxiedto your dedicated image server. The match is case-insensitive, so that.jpg and .JPG files are both acceptable, forexample.

RewriteRule (.*.(jpg|gif|png))$ http://images.example.com$1 [P,NC]

NE|noescape

By default, special characters, such as & and?, for example, will be converted to their hexcodeequivalent. Using the [NE] flag prevents that from happening.

RewriteRule ^/anchor/(.+) /bigpage.html#$1 [NE,R]

The above example will redirect /anchor/xyz to/bigpage.html#xyz. Omitting the [NE] will result in the #being converted to its hexcode equivalent, %23, which willthen result in a 404 Not Found error condition.

NS|nosubreq

Use of the [NS] flag prevents the rule from being used onsubrequests. For example, a page which is included using an SSI (ServerSide Include) is a subrequest, and you may want to avoid rewriteshappening on those subrequests.

Images, javascript files, or css files, loaded as part of an HTML page,are not subrequests - the browser requests them as separate HTTPrequests.

P|proxy

Use of the [P] flag causes the request to be handled bymod_proxy, and handled via a proxy request. Forexample, if you wanted all image requests to be handled by a back-endimage server, you might do something like the following:

RewriteRule (.*).(jpg|gif|png) http://images.example.com$1.$2 [P]

Use of the [P] flag implies [L] - that is, the request is immediatlypushed through the proxy, and any following rules will not beconsidered.

PT|passthrough

The target (or substitution string) in a RewriteRule is assumed to be afile path, by default. The use of the [PT] flag causes it to be treatedas a URI instead. That is to say, theuse of the [PT] flag causes the result of the RewriteRule to be passed back throughURL mapping, so that location-based mappings, such as Alias, for example, might have a chance to takeeffect.

If, for example, you have an Aliasfor /icons, and have a RewriteRule pointing there, you shoulduse the [PT] flag to ensure that the Alias is evaluated.

Alias /icons /usr/local/apache/icons
RewriteRule /pics/(.+).jpg /icons/$1.gif [PT]

Omission of the [PT] flag in this case will cause the Alias to beignored, resulting in a 'File not found' error being returned.

QSA|qsappend

When the replacement URI contains a query string, the default behaviorof RewriteRule is to discardthe existing query string, and replace it with the newly generated one.Using the [QSA] flag causes the query strings to be combined.

Consider the following rule:

RewriteRule /pages/(.+) /page.php?page=$1 [QSA]

With the [QSA] flag, a request for /pages/123?one=two will bemapped to /page.php?page=123&one=two. Without the [QSA]flag, that same request will be mapped to/page.php?page=123 - that is, the existing query stringwill be discarded.

R|redirect

Use of the [R] flag causes a HTTP redirect to be issued to the browser.If a fully-qualified URL is specified (that is, includinghttp://servername/) then a redirect will be issued to thatlocation. Otherwise, the current servername will be used to generate theURL sent with the redirect.

A status code may be specified, in the range 300-399, with a 302 statuscode being used by default if none is specified.

You will almost always want to use [R] in conjunction with [L] (that is,use [R,L]) because on its own, the [R] flag prependshttp://thishost[:thisport] to the URI, but then passes thison to the next rule in the ruleset, which can often result in 'InvalidURI in request' warnings.

S|skip

The [S] flag is used to skip rules that you don't want to run. Thiscan be thought of as a goto statement in your rewriteruleset. In the following example, we only want to run the RewriteRule if the requested URIdoesn't correspond with an actual file.

# Is the request for a non-existent file?
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# If so, skip these two RewriteRules
RewriteRule .? - [S=2]

RewriteRule (.*.gif) images.php?$1
RewriteRule (.*.html) docs.php?$1

This technique is useful because a RewriteCond only applies to theRewriteRule immediatelyfollowing it. Thus, if you want to make a RewriteCond applyto several RewriteRules, one possible technique is tonegate those conditions and use a [Skip] flag.

T|type

Sets the MIME type with which the resulting response will besent. This has the same effect as the AddType directive.

For example, you might use the following technique to serve Perlsource code as plain text, if requested in a particular way:

# Serve .pl files as plain text
RewriteRule .pl$ - [T=text/plain]

Or, perhaps, if you have a camera that produces jpeg images withoutfile extensions, you could force those images to be served with thecorrect MIME type by virtue of their file names:

# Files with 'IMG' in the name are jpg images.
RewriteRule IMG - [T=image/jpg]

Please note that this is a trivial example, and could be better doneusing <FilesMatch>instead. Always consider the alternatesolutions to a problem before resorting to rewrite, which willinvariably be a less efficient solution than the alternatives.

 
Copyright © 2009 The Apache Software Foundation         » Licensed under the Apache License, Version 2.0
(Sebelumnya) IntroductionTechnical details (Berikutnya)