Wednesday, 23 March 2011

Simple url rewriting, using Apache mod_rewrite

Some customers want to have nice, fancy, search engine friendly url-s in their browser, on their pages.
That is completely reasonable because it helps to better position the pages in search results.

For instance:


is not so tasty for search engine bots like the following:


If your web site runs on Apache web server than you could do it like this:

Create .htaccess file if there is not one already.

Write simple rule.

Write rule using regular expressions.

1. .htaccess file

Just a snapshot of some other code, you start from an empty .htaccess file

Look for it in your server root folder, public_html or htdocs. Open it using your text editor and put on a first line:

RewriteEngine on

Let us use it on above mentioned example:

2. Simple rule

Add this to .htaccess file:

RewriteRule ^about-us$ about_us.html

The part between ^ and $ is your url how you want it to be shown. The rest of the line is the actual file name of a document to be opened in browser.

3. A bit more power...

If you have url queries like in the first ugly url, you must use regular expressions:

RewriteRule ^([a-z]+)/([a-z]+)/chapter-one$ page1.php?subject=$1&field=$2

[a-z] matches all characters between lowercase a and z.
+ sign means any number of ocurrences, and brackets () define a variable to be used later in the rule.
So first ([a-z]+) in our example, matches 'geography' and the second one matches the word 'continents'.
These two variables are referenced in the real url by using $1 and $2. Numbers are assigned by the order of variable appearance.

If it does not work, perhaps you don't have mode_rewrite module enabled on your server. You can check that by executing a php file that contains only one function:


Under 'Loaded Modules' section look for mod_rewrite. If it is not listed there, you have to enable it by removing comment from corresponding line in httpd.conf file and restarting Apache server.
If you don't have access to httpd.conf then ask your hosting service to enable the module.

No comments:

Post a Comment