First I think it's best if I make it clear what a messy URL looks like:
http://www.example.com/index.php?page=news&id=01
And here is what a clean URL could look like:
http://www.example.com/news/first+blog+post/
http://www.example.com/tutorial:easy+php+tutorial
See how much better that looks? Here are a few reasons to use clean URLs:
- You can change where the page is but not lose any bookmarks (Thanks, to Mod_rewrite),
- They are easy to remember,
- Search engine's prefer it (Did you know that yahoo, msn and loads of other search engines (except google, thankfully) just ignore a page with a "?" in the URL),
- And of course they look a lot nicer.
All this is thanks to the .htaccess file and Mod_rewrite. So lets get on with it! First you open your code favourite editor and save a blank file called ".htaccess" and then add the line:
RewriteEngine On
This tells apache to turn Mod_rewrite on. Now we need to create our RewriteRule(s). My first examples rule will look like this
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9]+)$ index.php?page=$1&id=$2
I shall now explain this in a bit more detail:
- First we state that we're creating a rewrite by starting the line with: "RewriteRule",
- Then we use a "^" to state that we're creating our rule,
- Then we use Regular expressions to state what characters are allowed in the variable which we express in the next part,
- Then we use a $ sign to state the end of the clean URL ready to convert it to the messy URL to be read by the server,
- We tell the server what the URL should read and use $1, $2, $3 etc. To display the variables.
You might also choose to add this line too:
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/$ index.php?page=$1&id=$2
So that we may have a trailing slash on the URL.
There may be a few issues to rise with using a RewriteRule that looks like a set of directories. This is becase file's (such as the stylesheet and the images) will be linked to relative to the directory that the rule makes it look like it's in, as opposed to relative to where the file really is. This can be easily fixed by linking to such files from the site root instead. But I prefer to seperate the variables in the clean URL with a ":" as doesn't effect how you link to files and personally I think it looks better.
Something you may want to consider is when you have spaces in the variables in the clean URL. By modifying the regular expression in the URL to:
([a-zA-Z0-9+]+)
You enable there to be "+"'s in the clean URL, then when you get the url try this php code to turn them back into spaces:
<?php
$page = $_GET['page'];
$page = str_replace("+", " ", $page);
echo $page;
?>
I hope this tutorial has been useful to you!