John Main Logo

John Main

Code. Design. Hosting. Maintenance.

04
Feb '12

I know many many sites out there have tutorials on Mod Rewrite but I had to piece this together from a number of them and it seemed like a fairly common thing to want to do. If you’re using the classic controller/action/id schema for your site and want to prettify your links so that the values can be simply broken by slashes but you also want relative paths to any subfolders (for images, CSS etc) to work and you don’t want your subdomains to break then try this code in a .htaccess file in your web root. Of course you may need to change the naming of your root file and arguments.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f                        [NC,OR]
RewriteCond %{REQUEST_FILENAME} -d                        [NC]
RewriteRule .* -                                          [L]
RewriteRule ^([^/]+)/?$ index.php?controller=                                [QSA,L]
RewriteRule ^([^/]+)/([^/]+)/?$ index.php?controller=&action=                [QSA,L]
RewriteRule ^([^/]+)/([^/]+)/([0-9]+)/?$ index.php?controller=&action=&id=   [QSA,L]