Archive for October, 2009

How to: Use ModRewrite in .htaccess to include search engine friendly keywords in URLs

Monday, October 19th, 2009

Most CMS’s offer permalinks in the form of keywords within the URL. Using ModRewrite you can easily accomplish this.

First verify ModRewrite is enabled in Apache.

Create a test folder within your web root path and then create a file named .htaccess in your new folder containing this text:

RewriteEngine On

Now visit yourdomain.com/testfolder. If you get a 500 / Internal Server Error then you need to enable ModRewrite in Apache.

Once the page is loading without a 500 error, we can continue.

I’m going to show you how to turn an ugly URL like:

http://www.yourdomain.com/index.php?pageid=49382

to

http://www.yourdomain.com/pages/jewelry-and-watches/49382

First, let’s open .htaccess back up and add the following line:

RewriteRule ^([^/]+)/([0-9]+)[/]?$ index.php?keywords=$1&id=$2

Just to explain, the line above is rewriting any requests like:

/testfolder/these-are-my-keywords/123

to

index.php?keywords=these-are-my-keywords&id=123

Remember it’s not REDIRECTING, it’s REWRITING. This happens blindly to the user/spiders, so it can add true value to your web structures.

Next create a file named index.php in the same test folder with the following contents:

<?php
  //dump out $_GET variables
  print_r($_GET);
?>

You can now visit the page in your browser to see it in action.

Example URL:

http://www.yourdomain.com/testfolder/the-keywords-you-want/12345

You should get output from index.php like:

Array ( [keywords] => the-keywords-you-want [id] => 12345 )

I have posted a PHP function that will keywordize a page title or description.