Clean URLs with Apache mod_rewrite and PHP
Platform: PHP
Published May 15, 2012
Updated Feb 11, 2013
This is an easy to maintain method for creating clean urls without any file extensions. It's very good for hiding your underlying programming language and offers a more user friendly experience. It only uses a single series of mod_rewrite rules then all the rest of the logic can be accomplished within your script. You'll need mod_rewrite enabled and you can put these rules into your .htaccess or <VirtualHost> settings in httpd.conf.
RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d
RewriteRule ^.*\?{0,1}(.*)$ /index.php?$1 [QSA,L]Then within your PHP code you can handle the REQUEST_URI to determine what page to display. You can use query strings normally by accessing the $_REQUEST array.
$uri = $_SERVER[REQUEST_URI];
if(preg_match("/\/aboutus\//", $uri)) {
include('about_us.php');
}
else if(preg_match("/\/category\/([^\/]+)\//", $uri, $matches)) {
// Ex: /category/php/ or /category/java/
$category = $matches[1];
include('category.php');
}