How to set up .htaccess files for a CakePHP install

CakePHP is a very popular php/mysql based rapid development framework. It allows developers to quickly put together the “underpinnings” of a web application without having to re-invent the wheel. However, even the simplest of tools can have its little quirks, and CakePHP is no exception. CakePHP favors a “convention over configuration” style, which means that things have to be done a certain way, files have to be in the correct location, and classes have to have proper names. Like it says on the cover of the Hitchhiker’s Guide “Don’t Panic”. The basic layout of any CakePHP application is the same. Basically, there are three main parts to a Cake application:

1. The core CakePHP libraries, in /cake.
2. Your application code, in /app.
3. The application’s webroot, usually in /app/webroot.

The tough part is that each of those directories has its own .htaccess file:
In the Cake root directory:

RewriteEngine on
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]


In the App directory:

RewriteEngine on
RewriteRule ^$ webroot/ [L]
RewriteRule (.*) webroot/$1 [L]


In the webroot directory:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]


Now, the important thing to remember here is that changes generally need to be made in the proper .htaccess files. CakePHP looks at the root directory .htaccess file & the app directory to find the webroot directory. Then it uses the .htaccess in webroot to build url parameters. So, any redirections must be propagated through all three files. Much like event handling in Javascript.
A good example of how to handle this is when you are using a stats program that is installed in a subdirectory that you don’t want CakePHP to control. Let’s say you’re using awstats. In that case, the .htaccess file in your Cake root directory should look like this:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/awstats/
RewriteRule ^$ app/webroot/ [L]
RewriteCond %{REQUEST_URI} !^/awstats/
RewriteRule ^(.*)$ app/webroot/$1 [L]


Basically what that does is to stop CakePHP from redirecting for any request that ends with awstats. So now your stats program is outside CakePHP’s control. With this you should have a basic understanding of CakePHP & .htaccess. Good Luck.