Monday, April 02, 2012

Part 1: SEO-friendly links using .htaccess and PHP

A few weeks ago, I decided to try out some URL rewriting to use for some SEO-friendly links. I decided upon using Apache's mod_rewrite in an .htaccess file since I was developing using PHP on Apache. I wanted to be able to use SEO-friendly links on my website. In my solution, the key was using the .htaccess file to rewrite SEO-friendly links in the background back to the ugly URLs and using PHP to write the URLs to the SEO-friendly version for users and the browser to see.

Problem: I needed a way to convert my URLs to SEO-friendly versions.

Impact: The links are hard to remember and not very good for SEO.

Solution:
I used mod_rewrite and an .htaccess file to re-interpret SEO-friendly links back to their original formats.

As an example, the original format was something like:

http://www.example.com/index.php?page=a&id=256&title=my-title

The desired SEO-friendly format is:

http://www.example.com/a/256/my-title

The first thing to do is create a file called .htaccess and put this in the root folder of your website. At the top of your file put:

Options +FollowSymLinks
RewriteEngine On

RewriteEngine On turns on mod_rewrite. I also put -Indexes to prevent directory listing, so my first line is:

Options -Indexes +FollowSymLinks

To do the translation of SEO-friendly links back to original links, put the following line:

RewriteRule ^(.*)/([0-9]+)/([a-z0-9_-]+)$ index.php?page=$1&id=$2&title=$3 [L]

This defines the rewrite rule. The first bit between the ^ and the $ is the regular expression for the SEO-friendly link. It looks for anything/number/alphanumericwith_and-. The second bit is what the link will be translated to. The $1, $2, and $3 refer to the regular expression parts in the first bit respectively, so $1 refers to (.*), $2 refers ([0-9]+), and $3 refers to ([a-z0-9_-]+). Finally, the [L] flag at the end tells the server this is the last rule. This means that when the condition for this rule is met and the rule executed, don't continue checking other rules.

Instead of the above, you could also put ^(.*)/(.*)/(.*)$ for the regular expression. The only thing is that (.*) means any character except for line breaks.

To check if the link is translated correctly, type http://www.example.com/a/256/my-title (or your link, whatever you have) into the address bar of your browser and hit <Enter>. If your mod_rewrite is working and your rule is correct, it should go to the correct page.

To have the user see the SEO-friendly link you can just create a PHP function to write the URLs in search-engine-friendly format.

In my next post, I'll show how I did the same rule as above using a web.config file for IIS7 servers.

Sources:
.htaccess tricks and tips, http://corz.org/serv/tricks/htaccess2.php

0 comments:

Post a Comment