Clean URLs with Apache mod_rewrite and PHP

By Hawkee on May 15, 2012

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 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');
}

Comments

Sign in to comment.
Hawkee   -  Jun 14, 2012

@sean Yes, thank you. I added it to the title.

 Respond  
sean   -  Jun 14, 2012

It should be noted that this is strictly for Apache :)

 Respond  
PuNkTuReD   -  May 16, 2012

very interesting and helpful, thanks for the post hawkee.

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.