Tag Archives: htaccess rewrite url

List of .htaccess Examples

Some Good Official Tutorials

Sample .htaccess file from htaccess Google Group

Continue reading

Advanced mod_rewrite Expert Tricks

Are you an advanced mod_rewrite expert or guru? This article is for YOU too!

The following undocumented techniques and methods will allow you to utilize mod_rewrite at an “expert level” by showing you how to unlock its secrets.

Most if not all web developers and server administrators struggle with Apache mod_rewrite. It’s very tough and only gets a little easier with practice. Until Now! Get ready to explode your learning curve,….

Decoding Mod_Rewrite Variables

So when I realized my problem was that I didn’t know the value of the variable being tested by the RewriteCond, I set out to try and discover how to view those variables.. Keep in mind you can also use RewriteLogging, but its only allowed for root users who can edit the httpd.conf, this is .htaccess.

Setting Environment Variables with RewriteRule

I discovered a multitude of methods to set and view apache environment variables, using various modules and some core tricks, but the method that allows me to view the most environment variables is RewriteRule.. I wanted to use SetEnvIf more, but its just not as powerful as mod_rewrite, due to programming.

This code sets the variable INFO_REQUEST_URI to have the value of REQUEST_URI.

RewriteEngine On
RewriteBase /
RewriteRule .* - [E=INFO_REQUEST_URI:%{REQUEST_URI},NE]

Saving the Apache Variable Values

Now the trick is how to view that environment variable… The method I came up with is nice… We will send the environment variable value in an HTTP Header, as there isn’t much data manipulation/validation so you get an accurate look at the actual value.. At first I tried adding the variable value to a redirection using the query_string.. but a HTTP_USER_AGENT value doesn’t play well as a query_string.

Using RequestHeader in .htaccess

This code takes advantage of the incredible mod_headers apache module to actually ADD a whole new header to YOUR request. Seriously one of the coolest tricks I’ve found yet.. Its almost the same as being able to spoof POST requests! Since Headers can be protected data… especially the HTTP_COOKIE header..

RequestHeader set INFO_REQUEST_URI "%{INFO_REQUEST_URI}e"

Viewing the Variable Values

Now you can use any kind of server-run interpreter like perl, php, ruby, etc., to view all the variable values. All cgi-script handlers like those are able to view request headers..

PHP Code to access Apache Variables

Works even in safe-mode… any interpreter can view HTTP Headers! Note that each of these variables are added as HTTP headers to the request for the script.. kinda confusing.. So each variable sent as a header is prefixed with HTTP_ to denote it was a header.

<?php
header("Content-Type: text/plain");
$INFO=$MISS=array();
foreach($_SERVER as $v=>$r)
{
  if(substr($v,0,9)=='HTTP_INFO')
  {
    if(!empty($r))$INFO[substr($v,10)]=$r;
    else $MISS[substr($v,10)]=$r;
  }
}

/* thanks Mike! */
ksort($INFO);
ksort($MISS);
ksort($_SERVER);

echo "Received These Variables:\n";
print_r($INFO);

echo "Missed These Variables:\n";
print_r($MISS);

echo "ALL Variables:\n";
print_r($_SERVER);
?>

Time to Get Crazy

Just create the above php file on your site as /test/index.php or whatever, then create /test/.htaccess which should contain the below .htaccess file snippet. Now just request /test/index.php and be amazed!

Ok, so I’ve prepared the .htaccess code you can use to view the values of all these variables. Just add it to a .htaccess file and make a request. For this test I created an index.php file that printed out all the $_SERVER variables, and made requests to it.

RewriteEngine On
RewriteBase /
RewriteRule .* - [E=INFO_API_VERSION:%{API_VERSION},NE]
RewriteRule .* - [E=INFO_AUTH_TYPE:%{AUTH_TYPE},NE]
RewriteRule .* - [E=INFO_CONTENT_LENGTH:%{CONTENT_LENGTH},NE]
RewriteRule .* - [E=INFO_CONTENT_TYPE:%{CONTENT_TYPE},NE]
RewriteRule .* - [E=INFO_DOCUMENT_ROOT:%{DOCUMENT_ROOT},NE]
RewriteRule .* - [E=INFO_GATEWAY_INTERFACE:%{GATEWAY_INTERFACE},NE]
RewriteRule .* - [E=INFO_HTTPS:%{HTTPS},NE]
RewriteRule .* - [E=INFO_HTTP_ACCEPT:%{HTTP_ACCEPT},NE]
RewriteRule .* - [E=INFO_HTTP_ACCEPT_CHARSET:%{HTTP_ACCEPT_CHARSET},NE]
RewriteRule .* - [E=INFO_HTTP_ACCEPT_ENCODING:%{HTTP_ACCEPT_ENCODING},NE]
RewriteRule .* - [E=INFO_HTTP_ACCEPT_LANGUAGE:%{HTTP_ACCEPT_LANGUAGE},NE]
RewriteRule .* - [E=INFO_HTTP_CACHE_CONTROL:%{HTTP_CACHE_CONTROL},NE]
RewriteRule .* - [E=INFO_HTTP_CONNECTION:%{HTTP_CONNECTION},NE]
RewriteRule .* - [E=INFO_HTTP_COOKIE:%{HTTP_COOKIE},NE]
RewriteRule .* - [E=INFO_HTTP_FORWARDED:%{HTTP_FORWARDED},NE]
RewriteRule .* - [E=INFO_HTTP_HOST:%{HTTP_HOST},NE]
RewriteRule .* - [E=INFO_HTTP_KEEP_ALIVE:%{HTTP_KEEP_ALIVE},NE]
RewriteRule .* - [E=INFO_HTTP_MOD_SECURITY_MESSAGE:%{HTTP_MOD_SECURITY_MESSAGE},NE]
RewriteRule .* - [E=INFO_HTTP_PROXY_CONNECTION:%{HTTP_PROXY_CONNECTION},NE]
RewriteRule .* - [E=INFO_HTTP_REFERER:%{HTTP_REFERER},NE]
RewriteRule .* - [E=INFO_HTTP_USER_AGENT:%{HTTP_USER_AGENT},NE]
RewriteRule .* - [E=INFO_IS_SUBREQ:%{IS_SUBREQ},NE]
RewriteRule .* - [E=INFO_ORIG_PATH_INFO:%{ORIG_PATH_INFO},NE]
RewriteRule .* - [E=INFO_ORIG_PATH_TRANSLATED:%{ORIG_PATH_TRANSLATED},NE]
RewriteRule .* - [E=INFO_ORIG_SCRIPT_FILENAME:%{ORIG_SCRIPT_FILENAME},NE]
RewriteRule .* - [E=INFO_ORIG_SCRIPT_NAME:%{ORIG_SCRIPT_NAME},NE]
RewriteRule .* - [E=INFO_PATH:%{PATH},NE]
RewriteRule .* - [E=INFO_PATH_INFO:%{PATH_INFO},NE]
RewriteRule .* - [E=INFO_PHP_SELF:%{PHP_SELF},NE]
RewriteRule .* - [E=INFO_QUERY_STRING:%{QUERY_STRING},NE]
RewriteRule .* - [E=INFO_REDIRECT_QUERY_STRING:%{REDIRECT_QUERY_STRING},NE]
RewriteRule .* - [E=INFO_REDIRECT_REMOTE_USER:%{REDIRECT_REMOTE_USER},NE]
RewriteRule .* - [E=INFO_REDIRECT_STATUS:%{REDIRECT_STATUS},NE]
RewriteRule .* - [E=INFO_REDIRECT_URL:%{REDIRECT_URL},NE]
RewriteRule .* - [E=INFO_REMOTE_ADDR:%{REMOTE_ADDR},NE]
RewriteRule .* - [E=INFO_REMOTE_HOST:%{REMOTE_HOST},NE]
RewriteRule .* - [E=INFO_REMOTE_IDENT:%{REMOTE_IDENT},NE]
RewriteRule .* - [E=INFO_REMOTE_PORT:%{REMOTE_PORT},NE]
RewriteRule .* - [E=INFO_REMOTE_USER:%{REMOTE_USER},NE]
RewriteRule .* - [E=INFO_REQUEST_FILENAME:%{REQUEST_FILENAME},NE]
RewriteRule .* - [E=INFO_REQUEST_METHOD:%{REQUEST_METHOD},NE]
RewriteRule .* - [E=INFO_REQUEST_TIME:%{REQUEST_TIME},NE]
RewriteRule .* - [E=INFO_REQUEST_URI:%{REQUEST_URI},NE]
RewriteRule .* - [E=INFO_SCRIPT_FILENAME:%{SCRIPT_FILENAME},NE]
RewriteRule .* - [E=INFO_SCRIPT_GROUP:%{SCRIPT_GROUP},NE]
RewriteRule .* - [E=INFO_SCRIPT_NAME:%{SCRIPT_NAME},NE]
RewriteRule .* - [E=INFO_SCRIPT_URI:%{SCRIPT_URI},NE]
RewriteRule .* - [E=INFO_SCRIPT_URL:%{SCRIPT_URL},NE]
RewriteRule .* - [E=INFO_SCRIPT_USER:%{SCRIPT_USER},NE]
RewriteRule .* - [E=INFO_SERVER_ADDR:%{SERVER_ADDR},NE]
RewriteRule .* - [E=INFO_SERVER_ADMIN:%{SERVER_ADMIN},NE]
RewriteRule .* - [E=INFO_SERVER_NAME:%{SERVER_NAME},NE]
RewriteRule .* - [E=INFO_SERVER_PORT:%{SERVER_PORT},NE]
RewriteRule .* - [E=INFO_SERVER_PROTOCOL:%{SERVER_PROTOCOL},NE]
RewriteRule .* - [E=INFO_SERVER_SIGNATURE:%{SERVER_SIGNATURE},NE]
RewriteRule .* - [E=INFO_SERVER_SOFTWARE:%{SERVER_SOFTWARE},NE]
RewriteRule .* - [E=INFO_THE_REQUEST:%{THE_REQUEST},NE]
RewriteRule .* - [E=INFO_TIME:%{TIME},NE]
RewriteRule .* - [E=INFO_TIME_DAY:%{TIME_DAY},NE]
RewriteRule .* - [E=INFO_TIME_HOUR:%{TIME_HOUR},NE]
RewriteRule .* - [E=INFO_TIME_MIN:%{TIME_MIN},NE]
RewriteRule .* - [E=INFO_TIME_MON:%{TIME_MON},NE]
RewriteRule .* - [E=INFO_TIME_SEC:%{TIME_SEC},NE]
RewriteRule .* - [E=INFO_TIME_WDAY:%{TIME_WDAY},NE]
RewriteRule .* - [E=INFO_TIME_YEAR:%{TIME_YEAR},NE]
RewriteRule .* - [E=INFO_TZ:%{TZ},NE]
RewriteRule .* - [E=INFO_UNIQUE_ID:%{UNIQUE_ID},NE]

RequestHeader set INFO_API_VERSION "%{INFO_API_VERSION}e"
RequestHeader set INFO_AUTH_TYPE "%{INFO_AUTH_TYPE}e"
RequestHeader set INFO_CONTENT_LENGTH "%{INFO_CONTENT_LENGTH}e"
RequestHeader set INFO_CONTENT_TYPE "%{INFO_CONTENT_TYPE}e"
RequestHeader set INFO_DOCUMENT_ROOT "%{INFO_DOCUMENT_ROOT}e"
RequestHeader set INFO_GATEWAY_INTERFACE "%{INFO_GATEWAY_INTERFACE}e"
RequestHeader set INFO_HTTPS "%{INFO_HTTPS}e"
RequestHeader set INFO_HTTP_ACCEPT "%{INFO_HTTP_ACCEPT}e"
RequestHeader set INFO_HTTP_ACCEPT_CHARSET "%{INFO_HTTP_ACCEPT_CHARSET}e"
RequestHeader set INFO_HTTP_ACCEPT_ENCODING "%{INFO_HTTP_ACCEPT_ENCODING}e"
RequestHeader set INFO_HTTP_ACCEPT_LANGUAGE "%{INFO_HTTP_ACCEPT_LANGUAGE}e"
RequestHeader set INFO_HTTP_CACHE_CONTROL "%{INFO_HTTP_CACHE_CONTROL}e"
RequestHeader set INFO_HTTP_CONNECTION "%{INFO_HTTP_CONNECTION}e"
RequestHeader set INFO_HTTP_COOKIE "%{INFO_HTTP_COOKIE}e"
RequestHeader set INFO_HTTP_FORWARDED "%{INFO_HTTP_FORWARDED}e"
RequestHeader set INFO_HTTP_HOST "%{INFO_HTTP_HOST}e"
RequestHeader set INFO_HTTP_KEEP_ALIVE "%{INFO_HTTP_KEEP_ALIVE}e"
RequestHeader set INFO_HTTP_MOD_SECURITY_MESSAGE "%{INFO_HTTP_MOD_SECURITY_MESSAGE}e"
RequestHeader set INFO_HTTP_PROXY_CONNECTION "%{INFO_HTTP_PROXY_CONNECTION}e"
RequestHeader set INFO_HTTP_REFERER "%{INFO_HTTP_REFERER}e"
RequestHeader set INFO_HTTP_USER_AGENT "%{INFO_HTTP_USER_AGENT}e"
RequestHeader set INFO_IS_SUBREQ "%{INFO_IS_SUBREQ}e"
RequestHeader set INFO_ORIG_PATH_INFO "%{INFO_ORIG_PATH_INFO}e"
RequestHeader set INFO_ORIG_PATH_TRANSLATED "%{INFO_ORIG_PATH_TRANSLATED}e"
RequestHeader set INFO_ORIG_SCRIPT_FILENAME "%{INFO_ORIG_SCRIPT_FILENAME}e"
RequestHeader set INFO_ORIG_SCRIPT_NAME "%{INFO_ORIG_SCRIPT_NAME}e"
RequestHeader set INFO_PATH "%{INFO_PATH}e"
RequestHeader set INFO_PATH_INFO "%{INFO_PATH_INFO}e"
RequestHeader set INFO_PHP_SELF "%{INFO_PHP_SELF}e"
RequestHeader set INFO_QUERY_STRING "%{INFO_QUERY_STRING}e"
RequestHeader set INFO_REDIRECT_QUERY_STRING "%{INFO_REDIRECT_QUERY_STRING}e"
RequestHeader set INFO_REDIRECT_REMOTE_USER "%{INFO_REDIRECT_REMOTE_USER}e"
RequestHeader set INFO_REDIRECT_STATUS "%{INFO_REDIRECT_STATUS}e"
RequestHeader set INFO_REDIRECT_URL "%{INFO_REDIRECT_URL}e"
RequestHeader set INFO_REMOTE_ADDR "%{INFO_REMOTE_ADDR}e"
RequestHeader set INFO_REMOTE_HOST "%{INFO_REMOTE_HOST}e"
RequestHeader set INFO_REMOTE_IDENT "%{INFO_REMOTE_IDENT}e"
RequestHeader set INFO_REMOTE_PORT "%{INFO_REMOTE_PORT}e"
RequestHeader set INFO_REMOTE_USER "%{INFO_REMOTE_USER}e"
RequestHeader set INFO_REQUEST_FILENAME "%{INFO_REQUEST_FILENAME}e"
RequestHeader set INFO_REQUEST_METHOD "%{INFO_REQUEST_METHOD}e"
RequestHeader set INFO_REQUEST_TIME "%{INFO_REQUEST_TIME}e"
RequestHeader set INFO_REQUEST_URI "%{INFO_REQUEST_URI}e"
RequestHeader set INFO_SCRIPT_FILENAME "%{INFO_SCRIPT_FILENAME}e"
RequestHeader set INFO_SCRIPT_GROUP "%{INFO_SCRIPT_GROUP}e"
RequestHeader set INFO_SCRIPT_NAME "%{INFO_SCRIPT_NAME}e"
RequestHeader set INFO_SCRIPT_URI "%{INFO_SCRIPT_URI}e"
RequestHeader set INFO_SCRIPT_URL "%{INFO_SCRIPT_URL}e"
RequestHeader set INFO_SCRIPT_USER "%{INFO_SCRIPT_USER}e"
RequestHeader set INFO_SERVER_ADDR "%{INFO_SERVER_ADDR}e"
RequestHeader set INFO_SERVER_ADMIN "%{INFO_SERVER_ADMIN}e"
RequestHeader set INFO_SERVER_NAME "%{INFO_SERVER_NAME}e"
RequestHeader set INFO_SERVER_PORT "%{INFO_SERVER_PORT}e"
RequestHeader set INFO_SERVER_PROTOCOL "%{INFO_SERVER_PROTOCOL}e"
RequestHeader set INFO_SERVER_SIGNATURE "%{INFO_SERVER_SIGNATURE}e"
RequestHeader set INFO_SERVER_SOFTWARE "%{INFO_SERVER_SOFTWARE}e"
RequestHeader set INFO_THE_REQUEST "%{INFO_THE_REQUEST}e"
RequestHeader set INFO_TIME "%{INFO_TIME}e"
RequestHeader set INFO_TIME_DAY "%{INFO_TIME_DAY}e"
RequestHeader set INFO_TIME_HOUR "%{INFO_TIME_HOUR}e"
RequestHeader set INFO_TIME_MIN "%{INFO_TIME_MIN}e"
RequestHeader set INFO_TIME_MON "%{INFO_TIME_MON}e"
RequestHeader set INFO_TIME_SEC "%{INFO_TIME_SEC}e"
RequestHeader set INFO_TIME_WDAY "%{INFO_TIME_WDAY}e"
RequestHeader set INFO_TIME_YEAR "%{INFO_TIME_YEAR}e"
RequestHeader set INFO_TZ "%{INFO_TZ}e"
RequestHeader set INFO_UNIQUE_ID "%{INFO_UNIQUE_ID}e"

Mod_Rewrite Variables Decoded!

[API_VERSION] => 20020903:12
[AUTH_TYPE] => Digest
[DOCUMENT_ROOT] => /home/user/www_root/askapache.com
[HTTPS] => off
[HTTP_ACCEPT] => text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
[HTTP_COOKIE] => PHPSESSID=752ee6d56e15f305233e30045987e5ce568c034; __qca=1176541225-59967328-5223185;
[HTTP_HOST] => www.askapache.com
[HTTP_REFERER] => http://www.askapache.com/protest/index.php?askapache=awesomeness&you=rock
[HTTP_USER_AGENT] => Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.16) Gecko/20080702 Firefox/2.0.0.16
[IS_SUBREQ] => false
[QUERY_STRING] => e=404
[REMOTE_ADDR] => 22.162.144.211
[REMOTE_HOST] => 22.162.144.211
[REMOTE_PORT] => 4511
[REMOTE_USER] => administrator
[REQUEST_FILENAME] => /home/user/www_root/askapache.com/protest/index.php
[REQUEST_METHOD] => GET
[REQUEST_URI] => /protest/index.php
[SCRIPT_FILENAME] => /home/user/www_root/askapache.com/protest/index.php
[SCRIPT_GROUP] => daemonu
[SCRIPT_USER] => askapache
[SERVER_ADDR] => 208.113.134.190
[SERVER_ADMIN] => webmaster@askapache.com
[SERVER_NAME] => www.askapache.com
[SERVER_PORT] => 80
[SERVER_PROTOCOL] => HTTP/1.1
[SERVER_SOFTWARE] => Apache/2.0.61 (Unix) PHP/4.4.7 mod_ssl/2.0.61 OpenSSL/0.9.7e mod_fastcgi/2.4.2 DAV/2
[THE_REQUEST] => GET /protest/adf HTTP/1.1
[TIME] => 20080820014309
[TIME_DAY] => 20
[TIME_HOUR] => 01
[TIME_MIN] => 43
[TIME_MON] => 08
[TIME_SEC] => 09
[TIME_WDAY] => 3
[TIME_YEAR] => 2008

Request using HTTPS

[API_VERSION] => 20020903:12
[AUTH_TYPE] => Digest
[DOCUMENT_ROOT] => /home/user/www_root/askapache.com
[HTTPS] => on
[HTTP_ACCEPT] => text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
[HTTP_COOKIE] => PHPSESSID=752ee6d56e15f305233e30045987e5ce568c034; __qca=1176541225-59967328-5223185;
[HTTP_HOST] => www.askapache.com
[HTTP_REFERER] => http://www.askapache.com/protest/index.php?askapache=awesomeness&you=rock
[HTTP_USER_AGENT] => Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.16) Gecko/20080702 Firefox/2.0.0.16
[IS_SUBREQ] => false
[QUERY_STRING] => hi=you&whats=&amp;you
[REMOTE_ADDR] => 22.162.144.211
[REMOTE_HOST] => 22.162.144.211
[REMOTE_PORT] => 4605
[REMOTE_USER] => administrator
[REQUEST_FILENAME] => /home/user/www_root/askapache.com/protest/index.php
[REQUEST_METHOD] => GET
[REQUEST_URI] => /protest/index.php
[SCRIPT_FILENAME] => /home/user/www_root/askapache.com/protest/index.php
[SCRIPT_GROUP] => daemonu
[SCRIPT_USER] => askapache
[SERVER_ADDR] => 208.113.134.190
[SERVER_ADMIN] => webmaster@askapache.com
[SERVER_NAME] => www.askapache.com
[SERVER_PORT] => 443
[SERVER_PROTOCOL] => HTTP/1.1
[SERVER_SOFTWARE] => Apache/2.0.61 (Unix) PHP/4.4.7 mod_ssl/2.0.61 OpenSSL/0.9.7e mod_fastcgi/2.4.2 DAV/2
[THE_REQUEST] => GET /protest/index.php?hi=you&whats=&amp;you HTTP/1.1
[TIME] => 20080820015016
[TIME_DAY] => 20
[TIME_HOUR] => 01
[TIME_MIN] => 50
[TIME_MON] => 08
[TIME_SEC] => 16
[TIME_WDAY] => 3
[TIME_YEAR] => 2008

Emulating ErrorDocuments with Mod_Rewrite

The ErrorDocument directive is helpful because an errordocument is called differently then a normal file, and it contains special variables to help an admin debug.

I’ve wanted to use a RewriteCond + a RewriteRule to cause an Apache ErrorDocument to be displayed for a long time… I finally figured it out. Simply use the HTTP STATUS CODE trick in combination with a simple RewriteRule to trigger an Apache ErrorDocument.

This code emulates the internal 404 process Apache goes through.. If the file is not found it requests the /test/trigger-error/404 internally which triggers the 404 ErrorDocument.

source: Crazy Advanced Mod_Rewrite

More .htaccess

Introduction to .htaccess files

Your Web directory and its subdirectories can contain per-directory configuration files called .htaccess files. Whenever Stronghold (our Web server) receives a request for a file, it first looks for a file called .htaccess in that directory and its parent directories. If one is present, Stronghold considers the configuration directives within it before responding to the request. A .htaccess file works like this:

  • A .htaccess file must be a plain text file and contain no special formatting elements. Use a text editor to create your .htaccess file. If you create it with a word processor, be sure to save it as plain text.
  • A .htaccess file contains a list of configuration directives and nothing else.
  • If a .htaccess file contains any other information, it must be commented out in order to prevent errors
  • A .htaccess file must be saved in the top directory to which you want it to apply. The directives apply to that directory and its subdirectories.
  • If a subdirectory contains a .htaccess file, it overrides the .htaccess files of its parent directories.
  • The directives themselves should occupy one line each, like this:

ErrorDocument 404 errors/404.html
LanguagePriority en fr jp de
CookieTracking off
phpShowInfo on
FancyIndexing on
HeaderName header.html
ReadmeName readme.html
XBitHack full

Some valid .htaccess configuration directives are listed in the next sections. There are several types of configuration directives that control different server features.

FileTypes

The server’s general configuration already includes a wide range of mappings from MIME types to filename suffixes. If you are using a file format, encoding type, or language that is not already included in the server’s configuration, you can use these directives to enable them for your files.

AddType

* Syntax: AddType MIME-type file-suffix

With AddType, you can map MIME types to filename suffixes without editing the mime.types file.

AddEncoding

* Syntax: AddEncoding encoding-type file-suffix

AddEncoding matches filename suffixes to encoding types. When Stronghold sends an encoded file to a client, it includes a Content-Encoding header that gives the encoding type based on the filename’s suffix. The client can then determine the type of pre-processing required to decode the file for the user.

AddLanguage

* Syntax: AddLanguage language-type filename-suffix

When a client requests a document, it should include the Accept-Language: field in its request. The value is a two-letter abbreviation such as en, it, fr, or jp. AddLanguage maps these language types to filename suffixes. For example, if you have files named readme.html.fr and readme.html.jp, Stronghold knows which one to send to a French client and which to send to a Japanese client when each sends a request for readme.htm

Handlers

Handlers perform preprocessing on requested files. You can also use the ErrorDocument directive to customize the error messages that Stronghold sends when a request fails.

ErrorDocument

* Syntax: ErrorDocument error-code document

In the event of a problem or error, Stronghold does one of four things,

  • behave like NCSA HTTPD 1.3
  • output a customized message
  • redirect to a local URL to handle the problem or error
  • redirect to an external URL to handle the problem or error (except when the error code is 401)

All except the first are configured using ErrorDocument, which is followed by the HTTP response code and a message or URL. Messages in this context begin with a double quote (“), which does not form part of the message itself. Stronghold sometimes offers additional information regarding the problem or error. This can be embedded into the message using percentage signs (%).

URLs begin with a slash (/) for local URLs, or a full URL which the client can resolve. Examples:


ErrorDocument 500 /cgi-bin/tester
ErrorDocument 404 /cgi-bin/bad_urls.pl
ErrorDocument 403 “Sorry can’t allow you access today

AddHandler

* Syntax: AddHandler handler-name filename-suffix

This directive matches handlers to filename suffixes, and is often used in conjunction with Action. Handler-name can be the name of an existing handler or one that you create using the Stronghold API.

For example, you can use Stronghold’s as-is module by uncommenting this line in httpd.conf:

AddHandler send-as-is asis

With this handle enabled, Stronghold sends any file ending in .asis without adding an HTTP header. Your .asis files must include their own HTTP headers, followed by two carriage returns. This means that you can attach custom headers to your files without creating special CGI scripts to manage them.

You can also use this directive to create special handlers specifically for the Action directive, as described below.

SetHandler

* Syntax: SetHandler handler

SetHandler specifies a handler to be used for all files in a directory or location. There are six built-in values for handler:
Handler Description
cgi-script All files are treated as CGI scripts and processed by mod_cgi.
imap-file All files are treated as imagemap files and processed by mod_imap.
send-as-is Stronghold send all files without appending HTTP headers.
server-info All files are sent with server configuration information.
server-status All files are sent with server status information.
server-parsed All files are treated as server-parsed HTML, for server-side includes by mod_ssi.
type-map All files are treated as type maps for content negotiation by mod_negotiation.

Handler can also be a third-party or custom handler that you add with AddHandler.

Action

* Syntax: Action handler|media-type script

Action maps handlers or media types to the CGI scripts that process them. For example, if you do not want to use Stronghold’s internal imagemap feature, you could include

Code:
AddHandler imap-file .map
Action imap-file /cgi-bin/imap.cgi

This causes Stronghold to send all files ending in .map directly to the imap.cgi script. Thus, if Stronghold receives a request for

URL Rewriting

Stronghold can rewrite requested URLs that match a set of conditions. The rewritten request can be a URI, a URL, or a filepath with or without QUERY_STRING information. This powerful module can be used for an enormous variety of purposes, limited only by your imagination.

RewriteEngine

* Syntax: RewriteEngine on|off

This enables or disables the rewrite module for an object, host, or for the server. If you configure mod_rewrite for an object and later change your mind, set this directive to “off” rather than commenting out the rewrite directives.

RewriteOptions

* Syntax: RewriteOptions inherit

This sets special options for the rewrite configuration. Currently, there is only one option. “Inherit” forces an object to inherit the rewrite configuration of its parent. In the context of a .htaccess file, this means that the directory inherits the configuration in its parent’s .htaccess file.

RewriteBase

* Syntax: RewriteBase URL

This sets a base URL that mod_rewrite prepends to the result of a rewrite operation.

RewriteCond

* Syntax: RewriteCond test-string condition-pattern

RewriteCond defines a rule condition, and always precedes a RewriteRule directive. The rule given in RewriteRule applies only if the conditions given in RewriteCond are met. The rewrite module evaluates the test-string and matches it against condition-pattern. If they match, it applies the rule given in RewriteRule.

Test-string contains one or more of the following server variables:

  • HTTP_USER_AGENT
  • HTTP_REFERER
  • HTTP_COOKIE
  • HTTP_FORWARDED
  • HTTP_HOST
  • HTTP_PROXY_CONNECTION
  • HTTP_ACCEPT
  • REMOTE_ADDR
  • REMOTE_HOST
  • REMOTE_USER
  • REMOTE_IDENT
  • REQUEST_METHOD
  • SCRIPT_FILENAME
  • PATH_INFO
  • QUERY_STRING
  • AUTH_TYPE
  • DOCUMENT_ROOT
  • SERVER_ADMIN
  • SERVER_NAME
  • SERVER_PORT
  • SERVER_PROTOCOL
  • SERVER_SOFTWARE
  • SERVER_VERSION
  • TIME_YEAR
  • TIME_MON
  • TIME_DAY
  • TIME_HOUR
  • TIME_MIN
  • TIME_SEC
  • TIME_WDAY
  • API_VERSION
  • THE_REQUEST
  • REQUEST_URI
  • REQUEST_FILENAME
  • IS_SUBREQ

Condition-pattern is a standard, extended regular expression that mod_rewrite applies to an instance of the test-string. It can be preceded by an exclamation mark (!) to indicate a non-matching pattern, or substituted with one of the following flags:
Flag Description
-d Indicates that the test-string is a path to a directory
-f Indicates that the test-string is a path to a file
-s Indicates that the test-string is a path to a file with a size greater than zero
-l Indicates that the test-string is a path to a symbolic link
-F Indicates that the test-string should be a path to a valid file that is accessible via the current access controls for the path, and instructs mod_rewrite to use an internal subrequest to check this. This may decrease Stronghold’s performance.
-U Indicates that the test-string should be a valid URL that is accessible via the current access controls for its path, and instructs mod_rewrite to use an internal subrequest to check this. This may decrease Stronghold’s performance.

Any of these can also be prepended by an exclamation mark (!).

Condition-pattern can also be appended by a comma-separated, bracketed list of one of the following rule flags:
Rule Flag Description
nocase Makes test-string and condition-pattern case-insensitive
N Same as “nocase”
ornext Used with multiple RewriteCond directives to combine them with OR instead of the implicit AND.
OR Same as “ornext”

For example:

RewriteCond ${REMOTE_HOST} ^host1.* [OR]
RewriteCond ${REMOTE_HOST} ^host2.* [OR]
RewriteCond ${REMOTE_HOST} ^host3.*

RewriteRule

* Syntax: RewriteRule pattern substitute

RewriteRule defines the actual rules used to rewrite requested URLs that match conditions defined by RewriteCond. It can be used more than once, and multiple instances are evaluated in the order in which they appear.

Pattern is a POSIX regular expression that mod_rewrite applies to the current URL, whether it is the originally requested URL or a URL that has already been transformed by previous instances of RewriteRule. It may be prepended by an exclamation mark (!) to indicate a non-matching pattern, but a non-matching pattern cannot contain grouped wildcards.

Substitute is the string which mod_rewrite substitutes for any URL that matches the pattern. It can consist of

  • plain text,
  • pattern-group back-references ($N),
  • server variables (%{VARIABLE}), or
  • rewrite-map calls (${mapname:key|default}) to files defined by RewriteMap.

You can set special options for substitute by appending a comma-separated, bracketed list of these flags:

Flag Description
redirect[=status-code] Sends a status code between 300 and 400, specified by status-code. The default is 302.
R[=status-code] Same as “redirect”
forbidden Forces Stronghold to return a status code of 403 (“Forbidden”). This is useful for conditionally blocking URLs.
F Same as “forbidden”
gone Forces Stronghold to return a status code of 410 (“Gone”).
G Same as “gone”
proxy Forces the substitution part through the proxy module. The substitution string must be a valid URI. This is useful as a sophisticated alternative to the ProxyPass directive.
P Same as “proxy”
last Force the rewrite process to end here
L Same as “last”
next Reruns the rewrite process, starting with the first instance of RewriteRule and using the outcome of the current rewrite process as new input
N Same as “next”
chain Chains the current rule with the next rule, provided that the current rule matches
C Same as “chain”
type=mime-type Forces Stronghold to return the file as the specified MIME type
T=mime-type Same as “type”
nosubreq Indicates that the current rule applies only if the current request is not an internal subrequest
NS Same as “nosubreq”
passthrough Passes the substitution to the next handler, which should immediately follow the current RewriteRule
PT Same as “passthrough”
skip=n Skips the next n rules in a sequence if the current rule matches
S=n Same as “skip”
env=VARIABLE:VALUE Sets the environment variable VARIABLE to the value VALUE
E=VARIABLE:VALUE Same as “env”

User authentication

Stronghold includes authentication options:

AuthGroupFile

* Syntax: AuthGroupFile filename

AuthGroupFile specifies the filename that contains the list of authentication groups and the users they include.

AuthUserFile

* Syntax: AuthUserFile filename

AuthUserFile specifies the filename that contains the list of authenticated users and their crypt()-encrypted passwords.

Require

* Syntax: Require entity-name entity1 [entity2 ...]

This directive selects which authenticated users can access a directory. The allowed values are
Value Description
require user userid userid …
require group group-name group-name … Only users in the named groups can access the directory.
require valid-user All valid users can access the directory.

If require appears in a <Limit> section, then it restricts access to the named methods, otherwise it restricts access for all methods. For example:

AuthType Basic
AuthName somedomain
AuthUserFile /web/user
AuthGroupFile /web/groups
require group admin

Require must be accompanied by AuthName and AuthType directives, and directives such as AuthUserFile and AuthGroupFile (to define users and groups) in order to work correctly.

Host-based access control

In many cases, you may want to allow only certain hosts to access your hosts, directories, or files. Host-based access control is not as reliable as certificate authentication, because hackers can “spoof” hosts, pretending to send requests from one of the hosts you allow. However, we do recommend that you use these directives to control access to server status and configuration information, like this:


<Location /stronghold-status>
order deny, allow
deny from all
allow from yourhost.com
</Location>

<Location /stronghold-info>
order deny, allow
deny from all
allow from yourhost.com
</Location>

With this configuration, only users on your host can access server information.

order

* Syntax: order allow,deny|deny,allow|mutual-failure

Order, used in conjunction with allow and deny, provides host-based access control. The value is a comma-separated list that indicates which directive takes priority. The one that does not have priority usually takes the value “all.” For example,

Code:
order deny,allow

allows access from a few hosts and deny access from all other hosts. If you enter

Code:
order allow,deny

then you can deny access from a few hosts and allow access from all others. The order you choose depends on the nature of your site.

If the value is “mutual-failure,” then access is limited to hosts that appear in the allow list and not in the deny list.

Satisfy

* Syntax: Satisfy any|all

This sets the access policy if both allow and require are used. The value can be either “all” or “any.”

allow

* Syntax: allow from all|hostname1 [hostname2 ...]

The value for the allow directive can either be a list of hostnames which are allowed to access your server, or “all” to allow access from all hosts not excluded by the deny directive.

deny

* Syntax: deny from all|hostname1 [hostname2 ...]

The value for the deny directive can either be a list of hostnames which are denied access to your server, or “all” to deny access from all hosts not included by the allow directive.

Directory indexing

When Stronghold receives a request for a directory that does not have a default file, it creates a directory index in HTML and sends it to the client. These directives control the parameters of the generated index.

DirectoryIndex

* Syntax: DirectoryIndex filename1 [filename2 ...] /path/to/error/page

This sets the filename of the default index file for any directory. When a client sends a request URL to a directory but not a specific file, Stronghold returns the DirectoryIndex file. You can list any number of filenames, in order of priority, and Stronghold will look for each and return the first one it finds. By specifying the path to a file that contains an error message as the last item on the list, you can cause Stronghold to return that message if it finds none of the previous filenames. Alternatively, you can simply allow Stronghold to automatically create an HTML-formatted file list for the requested directory if it finds none of the files in the list.


Text:
  .           Any single character
  [chars]     Character class: Any character of the class ``chars''
  [^chars]    Character class: Not a character of the class ``chars''
  text1|text2 Alternative: text1 or text2

Quantifiers:
  ?           0 or 1 occurrences of the preceding text
  *           0 or N occurrences of the preceding text (N > 0)
  +           1 or N occurrences of the preceding text (N > 1)

Grouping:
  (text)      Grouping of text
              (used either to set the borders of an alternative as above, or
              to make backreferences, where the Nth group can
              be referred to on the RHS of a RewriteRule as $N)

Anchors:
  ^           Start-of-line anchor
  $           End-of-line anchor

Escaping:
  \char       escape the given char
              (for instance, to specify the chars ".[]()" etc.)

Mod_Rewrite Page to Remote Server

Introduction

RewriteRules can have their 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]

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

Each flag has a long and short form. 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.

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

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, will be skipped.

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 two optional fields.

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

By default, the lifetime of the cookie is the current browser session.

By default, the path for which the cookie will be valid is “/” – that is, 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 tells mod_rewrite to pass the request through unchanged) but sets a cookie called ‘frontdoor’ to a value of ‘yes’. The cookie is valid for any host in the .apache.org domain. It will be set to expire in 1440 minutes (24 hours) and will be returned for all URIs.

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 following example sets an evironment variable called ‘image’ to a value of ‘1’ if the requested URI is an image file. Then, that environment variable is used to exclude those requests from the access log.


RewriteRule %{REQUEST_URI} \.(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.

F|forbidden

Using the [F] flag causes Apache 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 rule uses the “-” syntax for the rewrite target, which means that the requested URI is not modified.

G|gone

Gone flag

H|handler

Handler flag

L|last

Last flag

N|next

Next round flag

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 URI.

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

No escape flag

NS|nosubreq

No internal subrequest flag

P|proxy

Proxy flag

PT|passthrough

Passthrough flag

QSA|qsappend

Query String Append flag

R|redirect

Redirect flag

S|skip

The [S] flag is used to skip rules that you don’t want to run. 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 URI doesn’t correspond with an actual file.


RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
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 RewriteRules, one possible technique is to negate those conditions and use a [Skip] flag.


T|type

Type flag

htaccess and .htaccess rewrite links

Apache Documentation

First, here are several links to the definitive source for Apache 1.3 and Apache 2.0 specifically related to using .htaccess, especially for redirecting URLs and blocking bad bots and spammers.

Apache 1.3
Apache 2.0

How to Use .htaccess, mod_rewrite, and Related (for Apache)

SRC: http://brainstormsandraves.com/archives/2005/10/09/htaccess/