04
Feb '12

Using Mod Rewrite to Make Pretty URLs the Safe Way

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]

2 Responses to “Using Mod Rewrite to Make Pretty URLs the Safe Way”

  1. TS Says:

    I always say, leave the URI handling to the application, send everything through in a neat way and let it work out how to handle it’s segments:

    RewriteRule ^(.*)$ index.php/$1 [L]

    Alternatively, you could rewrite (pun intended) your cod above:

    RewriteRule ^([^/]+)/([^/]+)/([0-9]+)/?$ index.php?controller=$1&action=$2&id=$3 [NC,QSA,L]

  2. john Says:

    A fair approach too 🙂
    The only issue with your alternative rewrite rule is that it won’t allow for optionally missing out the action or ID to allow the app to use the defaults.

Leave a Reply