Mod rewrite

From HalfgeekKB
Revision as of 14:34, 30 September 2005 by 161.253.47.104 (talk)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Template:Lowercase

mod_rewrite is a particularly useful tool for tricking the user agent. The point is to allow a user to access a URI by using another. The net effect is almost the same as a redirect, except that no redirect happens—the correct content is automatically passed through!

To get started, simply stuff a few lines into your .htaccess. The first must be

RewriteEngine on

This essentially boots up mod_rewrite. (Additionally, you can set this to off instead of commenting out all mod_rewrite lines in the file.)

Afterward, you add a rule that screws with the request URI:

RewriteRule ^(.*).txt$ $1.html [L]

This particular rule reroutes any requests to a .txt file to the .html file with the same basename. Simple! The first argument is obviously a regexp pattern. In Apache, as in most programs, the pattern syntax isn't as extensive as in Perl (you can't seem to use a trailing ? to indicate non-greed, for example) but it's still functional. You can lead the entire pattern with a ! to negate it.

The trailing [L] flag is optional; it (like a Perl last or a C break) means to skip the remaining rewrite directives. There are many other flags (see the Apache doc). Multiple flags on the same rule are separated by commas. If there are no flags, also omit the brackets.

[NC] makes the pattern case-insensitive (like Perl /i). [R] causes the use of an HTTP redirect to effect the rewrite.

Before the RewriteRule, you may have one or more RewriteCond lines:

 RewriteCond %{HTTP_USER_AGENT} !^CoralWebPrx/.*http://coralcdn\.org

Leading a RewriteRule with one or more RewriteConds has the effect of only running that RewriteRule if all of the RewriteCond lines apply. The first argument is a search string, and the second is the pattern. Adding an [OR] flag ties this and the following RewriteCond by OR instead of AND.

[NC] also works here.

%{HTTP_USER_AGENT} is one of many variables available for interpolation. The doc lists the available variables.

There are plenty more details and interesting uses; see the docs.

Examples

Only show the real file to Coral Cache

This example reroutes all requests for .txt files to the script redherring with the basename as the query string (for example, mono.txt leads to redherring?mono), unless it detects the Coral Cache user agent, in which case it gives the real .txt file. This sort of thing might be useful for using the URI on your own server to track the access before handing off the request to CCDN.

RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} !^CoralWebPrx/.*http://coralcdn\.org
RewriteRule ^(.*).txt$ redherring?$1 [L]

Available variables

See Also

Apache docs: mod_rewrite