Configuring mod_rewrite for the Front-Controller Pattern

When installing or creating a web application that implements the front controller pattern on an apache server, it is common to use mod_rewrite to redirect all traffic for non-existent resources to a the central dispatch file acting as the front controller.

Depending on where your decide to place your mod_rewrite rules, the required syntax can differ. The basic format of the rewrite configuration directives is as follows:

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule . /index.php [L]

In the preceding example, the rewrite engine is enabled, and two conditions are used to determine whether or not to run the rewrite rule. The first checks to see if the requested resource is not a file, and the second checks to see if the requested resource is not a directory. If both checks pass (ie: the resource does not exist), the rewrite rule will be executed and the file ‘/index.php’ will be served.

Depending on what your application requires, your actual rewrite rule may differ slightly. For example, the Zend Framework requires that the original request be fed back into the central dispatch file like this:

RewriteRule ^(.*)$ /index.php/$1

A common cause of problems is using the incorrect input in the RewriteCond directive. In all cases, it is correct to use either %{SCRIPT_FILENAME} or %{REQUEST_FILENAME} as they both contain the same text, but depending on where your rewrite rules are placed, you may need to prefix this with the contents of %{DOCUMENT_ROOT}. If your rules are placed in a per-directory context (<Directory>, <Location>, or .htaccess file), the document root is automatically prepended to the SCRIPT_FILENAME or REQUEST_FILENAME for you before the RewriteCond is processed. If your rules are located directly in a virtual host block, you will need to use the following syntax:

RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{SCRIPT_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}%{SCRIPT_FILENAME} !-d
RewriteRule . /index.php [L]
Chris Abernethy
PHP Wrangler, MySQL DBA, Linux SysAdmin and all around computer guy, developing LAMP applications since Slackware came on 10 floppy disks.

Got something to say? Go for it!