Understanding Apache htaccess

Page 1 - Introduction to RewriteRule

Skip to navigation

Apache Webserver
Jul
29

Apache has fast become one of the most commonly used web server solutions today. With its use comes the ability to manipulate the behaviour of your site in certain ways (server-side) from a type of file called .htaccess. This guide covers the various commands, and possibilities of using such a file.

Firstly, in order to use this, mod_rewrite must be enabled in httpd.conf. It is also recommended that the .htaccess file created is CHMOD'd to 644 so that the server can use it, but the browser cannot; preventing any sort of security hole from a user getting access to it.

A htaccess file acts from where it created, typically the root of the webserver, down to all the subfolders. Any folders that should not be affected by a htaccess above it should have it's own htaccess file that negates any rules that should not take affect.

Probably one of the most useful commands (otherwise known as a directive) available in a htaccess file, is that of RewriteRule - it is this that can be used rewrite one URL into another. For this to work, RewriteEngine On must be used first, as with any other Rewrite command.

RewriteEngine On
RewriteRule old.* new$1

The above example will redirect any urls that start with old to one where old has been replaced by new. For example, a request to /oldnews.php would change to /newnews.php by using the rule. As it uses a regular expression for the pattern, the .* tells Apache that multiple characters of any type should be matched - whatever is matched is assigned to $1 in the substitution. The syntax for this is as follows:

RewriteRule pattern substitution

Note: patterns use extended regular expressions

Using this methodology, it is easy to produce a rewrite rule for making friendly URLs for dynamic pages. For example, if you visit www.newearthonline/article/68 you will be automatically redirected to www.newearthonline.co.uk/index.php?page=article&article=68 - this is done using a rewrite rule.

RewriteEngine On
RewriteRule ^article/([0-9]+)/? article.php&article=$1   [R=301, L]

The rule itself will look for "article/" followed by 1 or more integers, and an optional forward slash. When this is matched it will take the integer and use it in the rewrite of the URL. The usage of the flags on the end of the RewriteRule is to signal that it is a permanent redirect (so absolute URLs are not needed), and to say it is the last rule to run for the request. These flags are covered in more detail later on.