Simple mod_rewrite rules

I'm in the process of writing both a new CMS and the framework to deliver it. From the outset we've wanted to use "nice" URLs, meaning that you won't see "index.php?c=something&id=12" in the log files, because that's not much use to the client. What we want is "some_page.html" showing up in the logs, so that when they use a statistics package they get meaningful data. I also want to have something like "/module/action/id" in the CMS, and hence the underlying framework. Ruby on Rails does this and I quite like it.

I knew that mod_rewrite was going to be the key, but I didn't know how easy it would be.

First step was to tell Apache that it was OK for me to have run-time configuration information in the .htaccess file. Within the "Directory" construct of the apache2.conf file (or the config file that you're including) enter the following:

AllowOverride All

Then I edited the .htaccess file in that direcroty and set a rewrite rule:

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*).html index.php?page=$1

This says "if you get a request for any page that ends in .html, send the request to index.php and pass the bit before the .html extension as a parameter called page". The bits above it say that it's OK to follow symbolic links on the filesystem, and turn the rewrite engine on (allowing me to set rules).

I then made an index.php that dumped the variables for me to test:

<?php

    echo "This has worked: here are the GET<br/>";
    print_r($_GET);

?>

Then hit some_page.html and you'll see that the URL doesn't change in the browser but index.php is clearly called, and the variable is passed through. The log files show an access for some_page.html. The next step would be to add some smarts that checks a database for the associated content page. You could make it even smarter by including a filename and an ID field in the page name, like some_page.3.html.

1 Comment so far

  1. dex on October 14th, 2005

    Thanks a lot for this.. There are so many tutorials out there but NONE of them worked.. This one, copy and pase and bang it worked!!!!

    Cheers again

    Dex