PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Creating Search Engine Friendly URLs In PHP

Using mod_rewrite as a 404 Handler

While the custom 404 handler is one of the most flexible methods for creating search-engine friendly URLs, the biggest problem with it when it comes to Apache is that POST data is not available (due to way Apache directs the request data when using ErrorDocument).

To get around this, we can use a combination of mod_rewrite and the custom 404 handler. The way this technique works is to use mod_rewrite to direct all requests to the specified script when the requested file was not found. This is achived using the following code (either in your .htaccess or httpd.conf.

Listing 10 Using mod_rewrite to foward requests that don't correspond to an existing file or directory (.htaccess)
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1

The first RewriteCond checks if the requested URL exists as a file on the filesystem. In mod_rewrite, -f refers to a file, while the bang is the "not" operator. Therefore, !-f means "if the request script filename does not exist as a file".

If the first rewrite_cond succeeds (that is, the requested file wasn't found), then Apache moves on to the next condition. The !-d directive means it the condition succeeds if the requested script does correspond to an existing directory on the server.

Finally, if both conditions succeed, the request is forwarded to the index.php file, as specified in the RewriteRule directive.

You can use the techniques in the previous section (on implementing a custom 404 handler) to read the URL and act appropriately. Using the technique outlined on this page you can now access request POST data.

In This Article


Article History

Jan 10, 2006
Initial article version
Feb 28, 2008
Added the "Using mod_rewrite as a 404 Handler" page to the article