CakePHP with out Mod_rewrite
Often in the course of development things have to be stretched, tweeked or just flat-out bent into place. After development of a CakePHP application a requirement was raised that Mod_Rewrite could not be installed. Hrmmmm! What a pain, all the URLs are already pretty, now it all has to be refactored. Or so you think!
The Solution
- Make sure .htaccess files are being read
- Change the servers default 404 page to point to mod_rewrite.php in /your_app/webroot
- Add the mod_rewrite.php file to /your_app/webroot
- Bask in your awesomeness
Modified .htaccess file
ErrorDocument 404 /mod_rewrite.php
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>
mod_rewrite.php file
<?php $url = ‘http://’.$_SERVER[‘HTTP_HOST’].’/index.php?url=’.$_SERVER[‘REQUEST_URI’] ; $fp = @fopen($url, “r”); $response = @stream_get_contents($fp); echo $response ; exit(); ?>
How it works
CakePHP really takes care of all the hard work for you. It does everything for you - the pushing and grunting and oh the magic.
With out mod_rewrite passing a “ugly” request to /index.php in the form of /index.php?url=/controller/action/params the web server 404’s. DOH! Done. Can’t find it. The server then looks up the default 404 directive and displays it. In this case we override the default server 404 page with the cakePHP mod_rewrite.php via the .htaccess file - cake takes care of the rest.
There is one problem with this method, the 404 directive does not pass any of the $_GET or $_POST vars. So if you have any forms on the site this method will not work. Best bet is to find a host that supports mod_rewrite.
Inspiration came from Spencer Yurdagül
