Search Engine Friendly URLs with PHP

Nov 11, 2008 | Tags: SEO, PHP | del.icio.us del.icio.us | digg Digg

3. Using Apache's mod_rewrite

All incoming requests, except those for static resources, need to go to a single index.php file. This script is the central point to display your articles. It retrieves the filename being requested, get the article that matches from the database, and then display the article. Note that if you already use index.php for your homepage, move it home.php or any other file you like.

We route all requests to index.php by using Apache's mod_rewrite. Put the lines below in a new file, name it .htaccess and place it in the webroot directory.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.php

The RewriteRule is very simple and can be interpreted as "for any url, except those for static resources, use index.php instead". With this configuration, requests for static pages like:

http://yourdomain.com/home.php
http://yourcomain.com/contact.php

still go to home.php and contact.php respectively, while other requests like:

http://yourdomain.com/Decline_of_The_Roman_Empire
http://yourdomain.com/final-war-of-the-roman-republic.html
http://yourdomain.com/Richard-1-of-England

will go to index.php instead.