You want an extension on that?

8/16/2010 9:00 AM By

Here’s a tasty little tidbit. Suppose you’ve got a series of PHP documents for your site, like index.php, about.php, and others. But you really want to have those pretty links like http://www.example.com/about/, etc. Fear not, some delightful mod_rewrite rules are here to save the day. So if we add this into your .htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.php [L,QSA]

You can visit http://www.example.com/about and you’ll actually be served http://www.example.com/about.php. Now, that’s all well and good, but why don’t we really take advantage of PHP, and instead of having separate documents for each page, serve everything from index.php and use a query variable to determine what the visitor actually sees? Put this in the .htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

And now, if you head to http://www.example.com/about, you’ll be served http://www.example.com/index.php?q=about. So how can we take advantage of this? How about something like this:

require_once('library.php');
switch ($_GET['q']) {
    case 'about':
        echo header('about page');
        break;
    default:
        echo header('home page')
        break;
}
include($_GET['q'] . '.php');
require('footer.php');

So while we still have the truly separate items broken down into separate files, we’ve consolidated as much common functionality as possible into the index.php file and the library.php file.

And why should we bother? Because other than image files (jpg, png, etc.), HTML files, and formats people actually deal with, extensions like php, cgi, asp, and other server-processed languages have little to no value to your visitors. So you give them shorter, easier-to-understand URLs, and if you ever decide to switch languages in the future, you don’t have to worry about your URLs.

Tags:

Comments are closed.