Home

Algorithmic Advent: 12 – Clean URLs with mod_rewrite

Published on 12 Dec 2010. Tagged with php, algorithmicadvent.

.htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

This forwards every non-existing resource to index.php.

index.php:

$baseUrl = ''; // Use this if your application resides in a sub directory
$path    = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

$path = substr($path, strlen($baseUrl));

/*
 * Associate URL path with logic code. (In a real world scenario, this would be
 * done much more sophisticatedly. Take a look at Zend_Router for instance.)
 */

switch ($path) {
    case '/':         echo 'Index page';   break;
    case '/contact':  echo 'Contage page'; break;
    case '/projects': echo 'Project page'; break;
    default:          echo 'Not mapped';   break;
}