Mod rewrite for a mvc structur

Sometimes you want correct url’s (such as www.maffelu.net/articles instead of www.maffelu.net?typ=articles) for various reasons. It could be that you want a close relation with google, or that you want to make it easier for users to distribute links to your pages.
Whatever the reason you’ll have to search for quite some time to figure out how to make these url’s valid on your server and in the end some pretentious nerd will give you the address to apaches homepage followed by RTFM!!!
In the end you have to parse through the endless documentation and if you don’t have access to the server error-log, you’ll end up tearing your hair off your head when all you get is a unknown server error upon failure.

To make things simpler, I’ve created a very basic .htaccess file you could use for a simple MVC structure:

 

RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_URI} !\.(css|jpg|gif|png|js|ttf|htm)$ [NC]
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/(.*)$ index.php?controller=$1&action=$2&id=$3 
[QSA,L]

RewriteCond %{REQUEST_URI} !\.(css|jpg|gif|png|js|ttf|htm)$ [NC]
RewriteRule ^([a-zA-Z0-9_-]+)/(.*)$ index.php?controller=$1&action=$2 [QSA,L]

RewriteCond %{REQUEST_URI} !\.(css|jpg|gif|png|js|ttf|htm)$ [NC]
RewriteCond %{REQUEST_URI} !test.php$ [NC]
RewriteRule ^(.*)$ index.php [QSA,L]

 

This let’s you create the following url’s:
www.maffelu.net/controller/action/id/
www.maffelu.net/controller/action/
www.maffelu.net/test.php *
www.maffelu.net
*sometimes it can be nice to have a test page

This also tells the server to ignore the rules for files with the extensions css, jpg, gif etc that shouldn’t be handled.

Also, if you have a folder with web services which really shouldn’t be bothered with this, you can add an exception to an entire folder like this:

RewriteCond %{REQUEST_URI} !\.(css|jpg|gif|png|js|ttf|htm)$ [NC]
RewriteCond %{REQUEST_URI} !webservices/ [NC]		#Ignore web services
RewriteRule ^([a-zA-Z0-9_-]+)/(.*)$ index.php?controller=$1&action=$2 [QSA,L]