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.


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.


* Syntax: AddType MIME-type file-suffix

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


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


* 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 and, 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 perform preprocessing on requested files. You can also use the ErrorDocument directive to customize the error messages that Stronghold sends when a request fails.


* 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/
ErrorDocument 403 “Sorry can’t allow you access today


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


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


* 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

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.


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


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


* Syntax: RewriteBase URL

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


* 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:


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


* 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:


* Syntax: AuthGroupFile filename

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


* Syntax: AuthUserFile filename

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


* 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

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

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


* 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,

order deny,allow

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

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.


* Syntax: Satisfy any|all

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


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


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


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

  .           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

  ?           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)

  (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)

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

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

Mod_Rewrite Page to Remote Server


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


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.


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 – []

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 domain. It will be set to expire in 1440 minutes (24 hours) and will be returned for all URIs.


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.


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.


Gone flag


Handler flag


Last flag


Next round flag


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))$$1 [P,NC]


No escape flag


No internal subrequest flag


Proxy flag


Passthrough flag


Query String Append flag


Redirect flag


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.


Type flag


One thought on “More .htaccess

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s