Using simple URIs with static files

This is probably the easiest way to get Apache to use friendly URIs. Keep your file extensions as they are, for instance calling a file example.html, but instead of linking to to it, link to example with no extension. To get this to work, add the following line to your .htaccess file:

Options +MultiViews

That's all there is to it, but it's worth noting that much more fun can be had with MultiViews. For instance, you can get Apache to serve compressed versions of your files without the people browsing your site having to do anything differently. You can also get Apache to give different versions of the file to different people, based on the language and MIME type preferences that their browsers have.

A way to use simple URIs with a database

These days, most information available from web servers is stored in databases rather than files. As long as you have the ability to use mod_rewrite, this doesn't stop you from using simple URIs.

You'll need to learn POSIX Regular Expressions in order to use mod_rewrite well, but the following addition to .htaccess should get you started:

# Use mod_rewrite
RewriteEngine On

# Allow hyphens, underscores, digits and lower case letters only
RewriteRule ^([-_0-9a-z]*)$ /index.php

# Don't allow anything else
ErrorDocument 404 /404.html

Then you can use the URI variable (taken from the HTTP Request-Line) in your chosen scripting language to work out which document to serve. The following example will work in a PHP script:

$location = ereg_replace("^/", "", $_SERVER['REQUEST_URI']); // Drop the forward slash
if ($location == "" || $location == "index.php") // Set a default DB entry to retrieve
{
  $location = "index";
}

Another way to use simple URIs with a database

If you need to have the requested location sent to your script as a variable, then the following .htaccess lines are a good place to start:

# Use mod_rewrite
RewriteEngine On

# Allow hyphens, underscores, digits and lower case letters only to become a variable
RewriteRule ^([-_0-9a-z]*)$ /index.php?page=$1

The following PHP example will make use of the variable being passed to it:

$location = $_GET['document']; // Get the location from the variable passed to the script
if ($location == "" || $location == "index.php") // Set a default DB entry to retrieve
{
  $location = "index";
}

Hopefully these examples should help you get started. As always, feel free to experiment and improve on them.

Log in or register to write something here or to contact authors.