Using Mod_Rewrite for Search Engine Friendly URLs

on Thu Aug 28 11:20:05 GMT 2008 in Webmaster Articles and viewed 7962 times

A common solution to making search-engine-friendly URIs using the Apache module mod_rewrite.


Dynamic urls are great. You know the kind; the ones with ?id=x&page=y. But unfortunately, search engines don’t follow links that look like that. So the solution would either be to go back to remaking every page over and over, or we could use the Apache module “mod_rewrite.” Now it’s important that it’s enabled or this just won’t work.

Mod_rewrite is a useful module that’s used to, well, rewrite urls. So instead of index.php?id=php it could be rewritten as tutorials/php.html. Using a .htaccess file, tutorials/php.html could be pointed to index.php?id=php. So the users se it as a static page but it’s still dynamic.

1. To start out with mod_rewrite, you need a .htaccess file. To create this, just use any text editor and create a file called .htaccess.

2. Next you need to tell it to use the mod_rewrite with a single line.


RewriteEngine On

3. Next we get into the meat.


RewriteRule [url that's be sent to the browser] [url it's being rewritten to]

So for this we need to rewrite tutorials/php.html to index.php?id=php, right? So for this we do:


RewriteRule tutorials/php.html index.php?id=php

Simple. The rule to rewrite is that tutorials/php.html goes to index.php?id=php.

4. You can also extend this a bit to be more dynamic with some RegEx. RegEx for those that don’t know is Regular Expressions. It can be used here.


RewriteRule tutorials/(.*).html index.php?id=$1

(.*) means a wild card. It’s also put into the url it’s being written to as $1. The first wildcard goes to $1, the second to $2, etc. It’s very useful so instead of creating many rules, you can have just one to write tutorials/php.html to index.php?id=php and tutorials/xhtml.html to index.php?id=xhtml very easily without many lines of code.

Final Code:


RewriteEngine On
RewriteRule tutorials/(.*).html index.php?id=$1

This can be used very effectively for search engine friendly urls. This doesn’t mean a sudden improvement in your rankings, but it does help since some search engines don’t crawl through uris like index.php?something=stuff&somethingelse=2.