Clean URLs with mod_rewrite

mod_rewrite

Using the mod_rewrite module you can link to a URL that has a concise name. For example rather than linking to tutorials.php?id=PHP you can link to tutorials/PHP.

.htaccess file

First, create a file and save it as .htaccess. Put this file in the directory you want the URL rewriting to take place (e.g. the main directory for the web site).

RewriteEngine On

Add the text above to the first line of the file to enable the URL rewriting.

Specifying rules

Next you can specify the rewrite rules using regular expressions. An example is below:

RewriteEngine On
RewriteRule ^tutorials/([^/\.]+)/?$ tutorials.php?id=$1 [L]

The example above means that a link to tutorials/PHP/ will load the document tutorials.php?id=PHP. The [L] flag means that the server will stop looking for rewrite rules once it has found one that matches. The $1 refers to the text found in the search, in the example above PHP.

RewriteEngine On
RewriteRule ^tutorials/([^/\.]+)/?$ tutorials.php?id=$1 [L]
RewriteRule ^downloads/([^/\.]+)/?$ downloads.php?id=$1 [L]

The example above means that a link to downloads/my-download/ loads the document downloads.php?id=my-download.

Regular expressions

In the example above the regular expression [^/\.]+ is used. This expression matches text that does not contain a forward slash or a full stop. This is needed as we want to catch the text after the tutorials/ and downloads/ folder.

Absolute URI’s

The example above changes the URL tutorials.php?id=PHP into tutorials/PHP/ which means that the files path is inside a directory it was not before. This means that any relative links in the document will not work. To solve this the HTML base element can be used inside the HEAD tag.

<base href="http://pixelcode.co.uk" />

The base element resolves any relative link to the base URL.

<base href="http://pixelcode.co.uk" />
<link href="main.css" rel="stylesheet" type="text/css" />
//The CSS file above will load from http://pixelcode.co.uk/main.css
The base element resolves all URI’s in the document including hyperlinks which means all URI’s need to be relative to the base URI.

Apache notes

For .htaccess files to work they need to be enabled in the servers .conf file:

https://httpd.apache.org/docs/current/mod/core.html#accessfilename
https://httpd.apache.org/docs/current/mod/core.html#allowoverride

Further Reading

Categories

Tags

No tags

Social