Making Clean URLs

First I think it’s best if I make it clear what a messy URL looks like:

http://www.tryangled.com/index.php?page=news&id=01

And here is what a clean URL could look like:

http://www.tryangled.com/news/first+blog+post/
http://www.tryangled.com/tutorial:easy+php+tutorial

Here are a few reasons to use clean URLs:

1. You can change where the page is but not lose any bookmarks (Thanks, to Mod_rewrite),
2. They are easy to remember,
3. 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),
4. And of course they look a lot nicer.

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

* 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

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;
?>

Posted by Mahesh ( Tryangled )

Leave a Reply

You must be logged in to post a comment.