RewriteRule Flags - Apache HTTP Server Version 2.4

Apache HTTP Server Version 2.4

Apache > HTTP Server > Documentation > Version 2.4 > Rewrite

# RewriteRule Flags

Available Languages: en | fr

This document discusses the flags which are available to the `RewriteRule` directive, providing detailed explanations and examples.

### See also

- Module documentation
- mod_rewrite introduction
- Redirection and remapping
- Per-directory Rewrites
- Virtual hosts
- Using RewriteMap
- When not to use mod_rewrite
- Technical details

## Introduction ¶

A `RewriteRule` can have its behavior modified by one or more flags. Flags are included in square brackets at the end of the rule, and multiple flags are separated by commas.

    RewriteRule pattern target [Flag1,Flag2,Flag3]

Each flag (with a few exceptions) has a short form, such as `CO`, as well as a longer form, such as `cookie`. While it is most common to use the short form, it is recommended that you familiarize yourself with the long form, so that you remember what each flag is supposed to do. Some flags take one or more arguments. Flags are not case sensitive.

Flags that alter metadata associated with the request (T=, H=, E=) have no effect in per-directory context, when a substitution (other than '-') is performed during the same round of rewrite processing.

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

## B (escape backreferences) ¶

The [B] flag instructs `RewriteRule` to escape non-alphanumeric characters before applying the transformation.

`mod_rewrite` has to unescape URLs before mapping them, so backreferences are unescaped at the time they are applied. Using the B flag, non-alphanumeric characters in backreferences will be escaped. For example, consider the rule:

For similar escaping of server variables, see the "escape" mapping-function

    RewriteRule "^search/(.*)$" "/search.php?term=$1"

Given a search term of 'x & y/z', a browser will encode it as 'x%20%26%20y%2Fz', making the request 'search/x%20%26%20y%2Fz'. Without the B flag, this rewrite rule will map to 'search.php?term=x & y/z', which isn't a valid URL, and so would be encoded as `search.php?term=x%20&y%2Fz=`, which is not what was intended.

With the B flag set on this same rule, the parameters are re-encoded before being passed on to the output URL, resulting in a correct mapping to `/search.php?term=x%20%26%20y%2Fz`.

    RewriteRule "^search/(.*)$" "/search.php?term=$1" [B,PT]

Note that you may also need to set `AllowEncodedSlashes` to `On` to get this particular example to work, as httpd does not allow encoded slashes in URLs, and returns a 404 if it sees one.

This escaping is particularly necessary in a proxy situation, when the backend may break if presented with an unescaped URL.

An alternative to this flag is using a `RewriteCond` to capture against %{THE_REQUEST} which will capture strings in the encoded form.

In 2.4.26 and later, you can limit the escaping to specific characters in backreferences by listing them: `[B=#?;]`. Note: The space character can be used in the list of characters to escape, but you must quote the entire third argument of `RewriteRule` and the space must not be the last character in the list.

    # Escape spaces and question marks.  The quotes around the final argument
    # are required when a space is included.
    RewriteRule "^search/(.*)$" "/search.php?term=$1" "[B= ?]"

To limit the characters escaped this way, see #flag_bne and #flag_bctls

See URL Encoding and Decoding for a full explanation of how Apache decodes URIs before pattern matching.

## BNP|backrefnoplus (don't escape space to +) ¶

The [BNP] flag instructs `RewriteRule` to escape the space character in a backreference to %20 rather than '+'. Useful when the backreference will be used in the path component rather than the query string.

    # Escape spaces to %20 in the path instead of + as used in form submission via
    # the query string
    RewriteRule "^search/(.*)$" "/search.php/$1" "[B,BNP]"

This flag is available in version 2.4.26 and later.

See URL Encoding and Decoding for background on how encoding is handled in the rewrite pipeline.

## BCTLS ¶

The [BCTLS] flag is similar to the [B] flag, but only escapes control characters and the space character. This is the same set of characters rejected when they are copied into the query string unencoded.

    # Escape control characters and spaces
    RewriteRule "^search/(.*)$" "/search.php/$1" "[BCTLS]"

This flag is available in version 2.4.57 and later.

## BNE ¶

The list of characters in [BNE=...] are treated as exclusions to the characters of the [B] or [BCTLS] flags. The listed characters will not be escaped.

    # Escape the default characters, but leave /
    RewriteRule "^search/(.*)$" "/search.php?term=$1" "[B,BNE=/]"

This flag is available in version 2.4.57 and later.

## C|chain ¶

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

    # Rewrite legacy product URLs to the new catalog app,
    # and add a tracking parameter — but only for the rewritten ones.
    RewriteRule "^/products/([0-9]+)$" "/catalog/item/$1" [C]
    RewriteRule "^/catalog/(.*)$" "/catalog/$1?via=legacy" [QSA]

Without the [C] flag, the second rule would also match requests that arrive at `/catalog/` directly. The chain ensures the second rule is only applied when the first rule matched.

## CO|cookie ¶

The [CO], or [cookie] flag, allows you to set a cookie when a particular `RewriteRule` matches. The argument consists of three required fields and five optional fields.

The full syntax for the flag, including all attributes, is as follows:

`[CO=NAME:VALUE:DOMAIN:lifetime:path:secure:httponly:samesite]`

If a literal ':' character is needed in any of the cookie fields, an alternate syntax is available. To opt-in to the alternate syntax, the cookie "Name" should be preceded with a ';' character, and field separators should be specified as ';'.

`[CO=;NAME;VALUE:MOREVALUE;DOMAIN;lifetime;path;secure;httponly;samesite]`

You must declare a name, a value, and a domain for the cookie to be set.

Domain
  The domain for which you want the cookie to be valid. This may be a hostname, such as `www.example.com`, or it may be a domain, such as `.example.com`. It must be at least two parts separated by a dot. That is, it may not be merely `.com` or `.net`. Cookies of that kind are forbidden by the cookie security model.

You may optionally also set the following values:

Lifetime
  The time for which the cookie will persist, in minutes.
  A value of 0 indicates that the cookie will persist only for the current browser session. This is the default value if none is specified.
  A negative value causes the cookie to be unset in the browser.
Path
  The path, on the current website, for which the cookie is valid, such as `/customers/` or `/files/download/`.
  By default, this is set to `/` - that is, the entire website.
Secure
  If set to `secure`, `true`, or `1`, the cookie will only be permitted to be translated via secure (https) connections.
httponly
  If set to `HttpOnly`, `true`, or `1`, the cookie will have the `HttpOnly` flag set, which means that the cookie is inaccessible to JavaScript code on browsers that support this feature.
samesite
  If set to anything other than `false` or `0`, the `SameSite` attribute is set to the specified value. Typical values are `None`, `Lax`, and `Strict`. Available in 2.4.47 and later.

Consider this example:

    RewriteEngine On
    RewriteRule   "^/index\.html"   "-" [CO=frontdoor:yes:.example.com:1440:/]

In the example give, the rule doesn't rewrite the request. The "-" rewrite target tells `mod_rewrite` to pass the request through unchanged. Instead, it sets a cookie called 'frontdoor' to a value of 'yes'. The cookie is valid for any host in the `.example.com` domain. It is set to expire in 1440 minutes (24 hours) and is returned for all URIs.

## DPI|discardpath ¶

The DPI flag causes the PATH_INFO that was appended to the rewritten URL-path to be discarded.

In per-directory context, the URL-path each `RewriteRule` compares against is the concatenation of the current URL-path and PATH_INFO.

The current URL-path can be the initial path as requested by the client, the result of a previous round of `mod_rewrite` processing, or the result of a prior rule in the current round of `mod_rewrite` processing.

In contrast, the PATH_INFO that is appended to the URL-path before each rule reflects only the value of PATH_INFO before this round of `mod_rewrite` processing. As a consequence, if large portions of the URL-path are matched and copied into a substitution in multiple `RewriteRule` directives, without regard for which parts of the URL-path came from the current PATH_INFO, the final URL-path may have multiple copies of PATH_INFO appended to it.

Use this flag on any substitution where the PATH_INFO that resulted from the previous mapping of this request to the filesystem is not of interest. This flag permanently forgets the PATH_INFO established before this round of `mod_rewrite` processing began. PATH_INFO will not be recalculated until the current round of `mod_rewrite` processing completes. Subsequent rules during this round of processing will see only the direct result of substitutions, without any PATH_INFO appended.

    # Request: /app/script.php/extra/path (PATH_INFO is /extra/path)
    # Without DPI, the substitution would see "script.php/extra/path"
    # and could inadvertently copy PATH_INFO into the result.
    RewriteRule "^script\.php(.*)$" "/new-app/handler$1" [DPI]

The [DPI] flag discards `/extra/path` so that only the substitution result (`/new-app/handler`) is passed to subsequent rules or the final request.

## E|env ¶

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

The full syntax for this flag is:

    [E=VAR:VAL]
    [E=!VAR]

`VAL` may contain backreferences (`$N` or `%N`) which are expanded.

Using the short form

`[E=VAR]`

you can set the environment variable named `VAR` to an empty value.

The form

`[E=!VAR]`

allows to unset a previously set environment variable named `VAR`.

Environment variables can then be used in a variety of contexts, including CGI programs, other RewriteRule directives, or CustomLog directives.

The following example sets an environment variable called 'image' to a value of '1' if the requested URL-path is an image file. Then, that environment variable is used to exclude those requests from the access log.

    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 as an example, not as a recommendation.

Setting environment variables for tracking rewrites

At times, we want to maintain some kind of status when we perform a rewrite. For example, you want to make a note that you've done that rewrite, so that you can check later to see if a request came via that rewrite. One way to do this is by setting an environment variable.

    RewriteEngine on
    RewriteRule   "^/horse/(.*)"   "/pony/$1" [E=rewritten:1]

Later in your ruleset you might check for this environment variable using a RewriteCond:

    RewriteCond "%{ENV:rewritten}"  =1

Note that environment variables do not survive an external redirect. You might consider using the [CO] flag to set a cookie.

### REDIRECT_ prefix after internal redirects

In per-directory context, a successful substitution triggers an internal redirect. When this happens, all environment variables set during the previous pass — including those created with `[E=VAR:VAL]` — are renamed with a `REDIRECT_` prefix. A variable you set as `rewritten` becomes `REDIRECT_rewritten` in the redirected request.

To test for the renamed variable, reference it with the prefix:

    RewriteRule   "^/horses/(.*)" "/ponies/$1" [E=rewritten:1]

    # In the next pass, the variable has been renamed:
    RewriteCond "%{ENV:REDIRECT_rewritten}" =1
    RewriteRule "^/ponies/(.*)" "-" [E=seen_redirect:1,L]

If the request is redirected multiple times, the prefix stacks: `REDIRECT_REDIRECT_rewritten`, and so on. See REDIRECT_ variables for the complete description of this mechanism.

## END ¶

Using the [END] flag terminates not only the current round of rewrite processing (like [L]) but also prevents any subsequent rewrite processing from occurring in per-directory context. This makes it the preferred flag for most per-directory rules.

In server or virtualhost context, [END] and [L] behave identically. The difference matters in per-directory context, where [L] stops the current pass but the ruleset is re-applied on the rewritten URL. This can cause infinite loops. [END] prevents all further rewrite processing, breaking the cycle.

    # In .htaccess: route all requests to a front controller
    # [L] would cause a loop here; [END] does not
    RewriteCond "%{REQUEST_FILENAME}" !-f
    RewriteCond "%{REQUEST_FILENAME}" !-d
    RewriteRule "^(.*)$" "/index.php" [END]

This does not apply to new requests resulting from external redirects.

See the Per-directory Rewrites discussion for a detailed explanation of why [L] behaves differently in per-directory context, and when [END] is the right choice.

## F|forbidden ¶

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

The following rule will forbid `.exe` files from being downloaded from your server.

    RewriteRule "\.exe"   "-" [F]

This example uses the "-" syntax for the rewrite target, which means that the requested URL-path is not modified. There's no reason to rewrite to another URL-path, if you're going to forbid the request.

When using [F], an [L] is implied - that is, the response is returned immediately, and no further rules are evaluated.

## G|gone ¶

The [G] flag forces the server to return a 410 Gone status with the response. This indicates that a resource used to be available, but is no longer available.

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

    RewriteRule "oldproduct"   "-" [G,NC]

When using [G], an [L] is implied - that is, the response is returned immediately, and no further rules are evaluated.

## H|handler ¶

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

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

The regular expression above - `!\.` - will match any request that does not contain the literal `.` character.

This can be also used to force the handler based on some conditions. For example, the following snippet used in per-server context allows `.php` files to be displayed by `mod_php` if they are requested with the `.phps` extension:

    RewriteRule "^(/source/.+\.php)s$" "$1" [H=application/x-httpd-php-source]

The regular expression above - `^(/source/.+\.php)s$` - will match any request that starts with `/source/` followed by 1 or n characters followed by `.phps` literally. The backreference $1 referrers to the captured match within parenthesis of the regular expression.

## L|last ¶

The [L] flag causes `mod_rewrite` to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed. This corresponds to the `last` command in Perl, or the `break` command in C. Use this flag to indicate that the current rule should be applied immediately without considering further rules.

In per-directory context, [L] stops the current pass through the ruleset, but the rewritten request may be re-processed from the top — which can cause loops. Use the [END] flag to prevent this, or see the Per-directory Rewrites document for a full discussion of the issue and alternative solutions.

The example given here will rewrite any request to `index.php`, giving the original request as a query string argument to `index.php`, however, the `RewriteCond` ensures that if the request is already for `index.php`, the `RewriteRule` will be skipped.

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

## N|next ¶

The [N] flag causes the ruleset to start over again from the top, using the result of the ruleset so far as a starting point. Use with extreme caution, as it may result in loop.

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

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

You can think of this as a `while` loop: While this pattern still matches (i.e., while the URL-path still contains an `A`), perform this substitution (i.e., replace the `A` with a `B`).

Use with extreme caution. If no termination condition is met, this flag will cause the rule to loop indefinitely. In most cases you should use [L] instead of [N], unless you truly intend iterative processing.

## NC|nocase ¶

Use of the [NC] flag causes the `RewriteRule` to be matched in a case-insensitive manner. That is, it doesn't care whether letters appear as upper-case or lower-case in the matched URL-path.

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

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

## NE|noescape ¶

By default, when a `RewriteRule` results in an external redirect, any characters in the output that are not in the following safe set will be converted to their hexcode (percent-encoded) equivalents:

- Alphanumeric characters: `A-Z`, `a-z`, `0-9`
- Special characters: `$-_.+!*'(),:;@&=/~`

For example, `#` would be converted to `%23`, and `?` to `%3F`. The `%` character is also escaped (to `%25`), which means that any percent-encoding already present in the substitution will be double-encoded.

Using the [NE] flag prevents this escaping, allowing characters such as `#` and `?` to pass through to the redirect URL unmodified.

    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 will then result in a 404 Not Found error condition.

See URL Encoding and Decoding for the full picture of how Apache encodes and decodes URIs during rewriting.

## NS|nosubreq ¶

Use of the [NS] flag prevents the rule from being used on subrequests. For example, a page which is included using an SSI (Server Side Include) is a subrequest, and you may want to avoid rewrites happening on those subrequests. Also, when `mod_dir` tries to find out information about possible directory default files (such as `index.html` files), this is an internal subrequest, and you often want to avoid rewrites on such subrequests. On subrequests, it is not always useful, and can even cause errors, if the complete set of rules are applied. Use this flag to exclude problematic rules.

To decide whether or not to use this rule: if you prefix URLs with CGI-scripts, to force them to be processed by the CGI-script, it's likely that you will run into problems (or significant overhead) on sub-requests. In these cases, use this flag.

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

    # Only rewrite direct requests to the front controller,
    # not subrequests from SSI includes or mod_dir.
    RewriteCond "%{REQUEST_FILENAME}" !-f
    RewriteCond "%{REQUEST_FILENAME}" !-d
    RewriteRule "^(.*)$" "/app/index.php?page=$1" [NS,L]

## P|proxy ¶

Use of the [P] flag causes the request to be handled by `mod_proxy`, and handled via a proxy request. For example, if you wanted all image requests to be handled by a back-end image 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 immediately pushed through the proxy, and any following rules will not be considered.

You must make sure that the substitution string is a valid URL (typically starting with `http://`hostname) which can be handled by the `mod_proxy`. If not, you will get an error from the proxy module. Use this flag to achieve a more powerful implementation of the `ProxyPass` directive, to map remote content into the namespace of the local server.

### Security Warning

Take care when constructing the target URL of the rule, considering the security impact of allowing the client influence over the set of URLs to which your server will act as a proxy. If any part of the target URL is derived from user input (backreferences, query strings, etc.), an attacker may be able to cause your server to make requests to arbitrary internal or external hosts. This is known as a Server-Side Request Forgery (SSRF) vulnerability. Ensure that the scheme and hostname part of the URL is either fixed, or does not allow the client undue influence.

### Performance warning

Using this flag triggers the use of `mod_proxy`, without handling of persistent connections as the default worker is used in this case, which does not handle connection pooling/reuse.

In order to use persistent connections you need to setup a `Proxy` block at least for the scheme and host part of the target URL containing a `ProxySet` directive where you e.g. set a timeout.

If you set it up with `ProxyPass` or `ProxyPassMatch` persistent connections will be used automatically.

Note: `mod_proxy` must be enabled in order to use this flag.

## PT|passthrough ¶

The target (or substitution string) in a RewriteRule is assumed to be a file path, by default. The use of the [PT] flag causes it to be treated as a URL-path instead. That is to say, the use of the [PT] flag causes the result of the `RewriteRule` to be passed back through URL mapping, so that location-based mappings, such as `Alias`, `Redirect`, or `ScriptAlias`, for example, might have a chance to take effect.

If, for example, you have an `Alias` for /icons, and have a `RewriteRule` pointing there, you should use 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 be ignored, resulting in a 'File not found' error being returned.

The `PT` flag implies the `L` flag: rewriting will be stopped in order to pass the request to the next phase of processing.

Note that the `PT` flag is implied in per-directory contexts such as `<Directory>` sections or in `.htaccess` files. The only way to circumvent that is to rewrite to `-`.

## QSA|qsappend ¶

When the replacement URL contains a query string, the default behavior of `RewriteRule` is to discard the 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 be mapped 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 string will be discarded.

## QSD|qsdiscard ¶

When the requested URL contains a query string, and the target URL does not, the default behavior of `RewriteRule` is to copy that query string to the target URL. Using the [QSD] flag causes the query string to be discarded.

This flag is available in version 2.4.0 and later.

Using [QSD] and [QSA] together will result in [QSD] taking precedence.

If the target URL has a query string, the default behavior will be observed - that is, the original query string will be discarded and replaced with the query string in the `RewriteRule` target URL.

    # Redirect old search URLs to the new path, discarding the query string.
    # /search?q=term&page=2  becomes  /find  (query string removed)
    RewriteRule "^/search" "/find" [QSD,R=301,L]

## QSL|qslast ¶

By default, the first (left-most) question mark in the substitution delimits the path from the query string. Using the [QSL] flag instructs `RewriteRule` to instead split the two components using the last (right-most) question mark.

This is useful when mapping to files that have literal question marks in their filename. If no query string is used in the substitution, a question mark can be appended to it in combination with this flag.

For example, if a legacy application expects a query string that itself contains a question mark:

    # Map /lookup/foo?bar to /app?type=foo?bar
    # Without [QSL], the first ? in the substitution would split the
    # path, producing /app with query string type=foo?bar incorrectly.
    # With [QSL], the LAST ? is used as the delimiter.
    RewriteRule "^/lookup/(.*)" "/app?type=$1" [QSL,PT]

Without [QSL], the substitution `/app?type=foo?bar` would be split at the first `?`, losing the literal question mark in the value.

This flag is available in version 2.4.19 and later.

## 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, including `http://servername/`) then a redirect will be issued to that location. Otherwise, the current protocol, servername, and port number will be used to generate the URL sent with the redirect.

Any valid HTTP response status code may be specified, using the syntax [R=305], with a 302 status code being used by default if none is specified. The status code specified need not necessarily be a redirect (3xx) status code. However, if a status code is outside the redirect range (300-399) then the substitution string is dropped entirely, and rewriting is stopped as if the `L` were used.

In addition to response status codes, you may also specify redirect status using their symbolic names: `temp` (default), `permanent`, or `seeother`.

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

Note: httpd only supports status codes that are included in the HTTP spec. Using an unrecognized status code will result in a 500 error and error log message.

### [R=4xx] does not serve the substitution

When a status code outside the 300-399 range is specified (e.g., `[R=403]` or `[R=410]`), the substitution string is ignored. The URL you wrote as the target is not served to the client. Instead, httpd returns the specified status code and handles it through the normal error response path (including any configured `ErrorDocument`). If you want to deny access, the [F] and [G] flags are clearer ways to express the same intent.

    # Redirect requests for the old docs path to the new location.
    RewriteRule "^/docs/(.*)$" "http://docs.example.com/$1" [R=301,L]

## S|skip ¶

The [S] flag is used to skip rules that you don't want to run. The syntax of the skip flag is [S=N], where N signifies the number of rules to skip (provided the `RewriteRule` and any preceding `RewriteCond` directives match). This can be thought of as a `goto` statement in your rewrite ruleset. In the following example, we only want to run the `RewriteRule` if the requested URL-path doesn'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 the `RewriteRule` immediately following it. Thus, if you want to make a `RewriteCond` apply to several `RewriteRule`s, one possible technique is to negate those conditions and add a `RewriteRule` with a [Skip] flag. You can use this to make pseudo if-then-else constructs: The last rule of the then-clause becomes `skip=N`, where N is the number of rules in the else-clause:

    # Does the file exist?
    RewriteCond "%{REQUEST_FILENAME}" !-f
    RewriteCond "%{REQUEST_FILENAME}" !-d
    # Create an if-then-else construct by skipping 3 lines if we meant to go to the "else" stanza.
    RewriteRule ".?"                  "-" [S=3]

    # IF the file exists, then:
        RewriteRule "(.*\.gif)"  "images.php?$1"
        RewriteRule "(.*\.html)" "docs.php?$1"
        # Skip past the "else" stanza.
        RewriteRule ".?"         "-" [S=1]
    # ELSE...
        RewriteRule "(.*)"       "404.php?file=$1"
    # END

It is probably easier to accomplish this kind of configuration using the `<If>`, `<ElseIf>`, and `<Else>` directives instead.

## T|type ¶

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

For example, you might use the following technique to serve Perl source 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 without file extensions, you could force those images to be served with the correct 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 done using `<FilesMatch>` instead. Always consider the alternate solutions to a problem before resorting to rewrite, which will invariably be a less efficient solution than the alternatives.

If used in per-directory context, use only `-` (dash) as the substitution for the entire round of `mod_rewrite` processing, otherwise the MIME-type set with this flag is lost due to an internal re-processing (including subsequent rounds of `mod_rewrite` processing). The `L` flag can be useful in this context to end the current round of `mod_rewrite` processing.

## UnsafeAllow3F ¶

Setting this flag is required to allow a rewrite to continue If the HTTP request being written has an encoded question mark, '%3f', and the rewritten result has a '?' in the substitution. This protects from a malicious URL taking advantage of a capture and re-substitution of the encoded question mark.

    # A PHP front controller that routes all requests via a query parameter.
    # Without UnsafeAllow3F, a request like /page%3Fname=test would return
    # 403 Forbidden because the rewritten substitution contains '?' while
    # the original request contains an encoded '%3F'.
    RewriteCond "%{REQUEST_FILENAME}" !-f
    RewriteCond "%{REQUEST_FILENAME}" !-d
    RewriteRule "(.+)" "index.php?route=$1" [L,QSA,UnsafeAllow3F]

This flag exists because of CVE-2024-38474. Use it only on rules where you are certain that user-supplied `%3F` in the request cannot be exploited to manipulate the query string of the substitution target. Prefer restructuring URLs to avoid encoded question marks where possible.

## UnsafePrefixStat ¶

Setting this flag is required in server-scoped substitutions start with a variable or backreference and resolve to a filesystem path. These substitutions are not prefixed with the document root. This protects from a malicious URL causing the expanded substitution to map to an unexpected filesystem location.

Available in Apache HTTP Server 2.4.60 and later.

    # This rule starts the substitution with a backreference.
    # Since 2.4.60, this is rejected by default to prevent the expanded
    # path from escaping the document root (CVE-2024-38475).
    # Only add UnsafePrefixStat after verifying the substitution cannot
    # resolve to a filesystem path outside your web root.
    RewriteRule "^/mirror/(.+)$" "$1" [PT,UnsafePrefixStat]

This flag exists because of CVE-2024-38475. Without it, a substitution beginning with a backreference or variable that happens to match an existing filesystem path could allow requests to escape the document root. Use this flag only after confirming that the substitution is adequately constrained.

## UNC ¶

Setting this flag prevents the merging of multiple leading slashes, as used in Windows UNC paths. The flag is not necessary when the rules substitution starts with multiple literal slashes.

Available in Apache HTTP Server 2.4.63 and later.

    # On Windows, rewrite to a UNC file share using a variable.
    # Without [UNC], the leading slashes in the substitution would be
    # collapsed (//server/share becomes /server/share).
    RewriteCond "%{HTTP_HOST}" "^(.+)\.internal$"
    RewriteRule "^/shared/(.*)$" "//%1/fileshare/$1" [UNC]

This flag is only relevant on Windows. It prevents Apache from merging the leading double slash (`//`) that denotes a UNC path when the path is constructed from a backreference or variable. If the substitution begins with literal double slashes, no flag is needed.

Available Languages: en | fr