header
 
     
 
pixel
pixel pixel

Using .htaccess to rewrite your dynamic URLs

URL rewriting let you hide all your ugly variable ridden URLs and instead present to the world clean, static URLs. For example (taken from ozziebuy.com.au), the URL:
http://www.ozziebuy.com.au/document.php?Filename=how_to_register
can take the form:
http://www.ozziebuy.com.au/how_to_register.htm

There are many advantages to using dynamic URLs. As they let your webpages appear as static HTML pages, search engines are more likely to index them (some search engines get jittery at indexing dynamic pages). They're more intuitive and user-friendlier for users. It allows you to put all your content into a database and greatly reduces the number of PHP pages to maintain (I'm a big fan of separating content and code). And crucially, it allows you (or your clients) to edit your website via a web based content management system rather than depending on HTML editors and ftp programs.

Sold to the idea yet? In this tutorial, I'll reduce an entire HTML website to a single PHP page. The first step is to create a MySQL table 'page' that will store your webpage content and for the sake of this exercise, insert one sample page:
CREATE TABLE `page` (
  `PageId` int(11) NOT NULL auto_increment,
  `Title` varchar(100) NOT NULL default '',
  `Filename` varchar(30) NOT NULL default '',
  `Content` text NOT NULL,
  PRIMARY KEY  (`PageId`)
) TYPE=MyISAM PACK_KEYS=0 AUTO_INCREMENT=20 ;

INSERT INTO page ( Title , Filename , Content ) 
VALUES ( 'Homepage', 'index', 'Content to go on homepage');

Next is to create a new text file and copy and paste the following content. Then save the text file as .htaccess (note - it mustn't have a .txt extension):

.htaccess
RewriteEngine on
RewriteRule ^([0-9a-zA-Z-_]*).htm$ index.php?Filename=$1 [L]

What this does is use a regular expression ^([0-9a-zA-Z\-\_]*).htm$ to look for any webpage that takes the form filename.htm. It then extracts the first part of the filename (whatever is in front of the period) and loads instead a page index.php?Filename=$1 where it replaces the $1 with the first part of the filename. In other words, if you visited the URL www.ozziebuy.com.au/how_to_register.htm, the regular expression would extract how_to_register and instead load the page www.ozziebuy.com.au/document.php?Filename=how_to_register. Now we need the webpage index.php:

index.php
// include and instantiate a database class
// see http://www.tipsntutorials.com/tutorials/PHP/76/ for more code on this
include ('includes/database.php');
$db = new Database;

// if no Filename is defined, send them to the homepage (alternatively you could send them to an error page)
if (!isset($_GET['Filename']) || !$_GET['Filename'])
    $Filename = 'index';
else
    $Filename = $_GET['Filename'];

// retrieve page content from database
$Query = "SELECT * FROM page WHERE Filename = '$Filename'";
$db->query($Query);

// only show content if we found something
if ($db->numRows())
    {
    // display title and content of this page
    $db->singleRecord();
    echo "<h1>".$db->Record['Title']."</h1>rn";
    echo $db->Record['Content'];
    } // end if we have page content
else
    {
    echo "<h1>Page Error</h1>rn There is no page at this address.";
    } // end if we have no page content

Apologies but I use a database class explained in another tutorial for all my database functions (saves me repeating lots of code). If no Filename is specified in the URL, I assume one myself - 'index' in this case. Of course, you would have to have a page in your database with Filename 'index' for this to work. Alternatively you might want to send them to an error page or sitemap. Then it's a simple matter of finding the page in the database that matches the filename. If a page is found, display the title and content. If not, display an error message. And there you have it - all your HTML pages reduced to a PHP page, a .htaccess file and a MySQL database. Now all you have to do is whip up a content management system... easy! :-)


Unhelpful Helpful Rating 5.0 (score out of 5, no. of ratings: 1)
Comments
Comment by Rhys on 2007-06-17
Thank you for this tutorial. The idea of simplifying the URL to be more user friendly, and keeping things simple with a database is exciting. This should improve my websites. Thanks again!!

Post a Comment
Name
Email
(optional)
Comment
RatingUnhelpful Helpful
Security Image* (this is just to prevent spam submissions)
Security Image