Monday, August 25, 2008

SEO Friendly URLs

Let’s say you have a site which has movie reviews. To display a unique review, you would have a PHP page, for example review.php, which obtains the id of the review and shows the title and description of that review. So, if you want to see the review with id 45, you need to access the following URL:

Do you see a problem with this? No? Are you sure? Ok, then I’ll have to explain it. With that type of URL, you are not able to know anything about the review. It could be a review for “Casablanca” just as easily as it could a review for “Ace Ventura: Pet Detective”. And that’s not the biggest problem; it is also a bad SEO URL!

How can you fix this? Use SEO Friendly URLs.

Requirements: Apache (with mod_rewrite module) installed on your server (most hosting services already have this).

Step 1: Insert the following code on you PHP script

function StrToSearchFriendlyURL($s) {
if(!$s) return 'page';

$s = strtolower(htmlentities($s, ENT_QUOTES, $GLOBALS['CHARSET']));
$s = preg_replace('/&(.)(?:acute|cedil|circ|ring|tilde|uml|grave|elig|slash);/', '\\1', $s);
$s = preg_replace('/\W+/', '_', html_entity_decode($s));
$s = preg_replace('/_{2,}/','_',$s);
$s = trim($s,'_');

if(!$s) $s = 'page';

return $s;
Step 2: Apply the above function to your regular URLs to make them SEO Friendy.

Step 3: When inserting the new URLs on your page, add a dash (-), the review id and html extension at the end.


<a href="{SEO_friendly_URL}-{id}.html">{$review_title}</a>

Step 4: Create a .htaccess file with the following content.

Options +FollowSymLinks

RewriteEngine On
RewriteRule ^[^-]+-([0-9]+)\.html$ review.php?id=$1 [L]

Step 5: Place the .htaccess file on your site’s document root.

That’s it! The URLs on your site will now look something like this: which will be interpreted by Apache like

More about mod_rewrite:
More about .htaccess files:

1 comment:

marcus said...

Back at the time I was still studying PHP, I was taught how to code SEO friendly URLs, for the ones who are working in a SEO web design company who also looks for SEO friendly URL.