URL-rewriting configuration for the Zend Framework

Recently I gave a talk about the Zend Framework. Part of that talk was an introduction to the suggested filesystem layout of projects based on the Zend Framework. I also gave hints about the configuration of the URL-rewriting to allow the mapping of requested URLs to a controller/action that would process the request. Read on to find out more about possible URL-rewriting configurations for the Zend Framework.

In the quickstart-section the ZF manual suggests the following configuration for Apache’smod_rewrite.

RewriteEngine on
RewriteRule !\.(js|ico|gif|jpg|png|css)$ index.php

This rewrite-rule is pretty simple. You forward every non-resource request (everything but scripts, stylesheets, etc.) to the ZF front-controller. If you wanted to prevent requests to for instance PDF files from being routed to the front-controller script you could add the “pdf” extension to the list. The more exceptions from the rule the more tedious this is. Therefore I suggested another configuration for the rewrite-rules in my talk (see the image):

Zend Framework directory layout

Zend Framework directory layout

The configuration shown in the image activates the rewrite-engine for the root-directory of the project and forwards every request to the front-controller (index.php). Directories containing libraries or application sources are defined to be inaccessible by the browser (deny from all). Only for the public-directory that contains resources (images, stylesheets, etc.) the rewrite-engine is disabled to allow access by the browser.

Both recommendations have one major drawback: All requests are routed to the front-controller script. It is not easily possible to put a directory (containing php-files or whatever) into the root-directory and allow access from the browser. You would always have to disable the rewrite-engine first. One attendee of my Zend Framework talk gave me a hint that mod_rewrite allows to test whether a file or directory exists. Thus it would be possible to route only requests for non-existent files/directories to the front-controller. A possible rewrite-configuration could look like this:

RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php

A little too late I noticed that the ZF manual even describes that kind of configuration in the RewriteRouter section. IMHO they hid that one really good. ;-) I think it would have been more helpful if they had already mentioned it in the quickstart section. I suggest you use the preceding configuration for the root-directory of your ZF project and deny access for all other directories no web-browser must see (application source-files, libraries, etc.). You won’t need .htaccess files for public directories as they aren’t affected by the rewrite-rule for the front-controller any longer.

Posted in Development, PHP, June 2nd, 2007

Leave a Reply