Sunday, July 10, 2011

rewrite rule in a .htaccess file

I've been using Zend framework for a while but never spent time on figuring out how the rewrite rules work. I simply copy them from other places and as long as it works, i don't look at them. But now let's have a look at them carefully. 

ErrorDocument 404 /index.php
DirectoryIndex index.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1

Let's check through the rules line by line.

ErrorDocument 404 /index.php tells Apache that the index.php file should deal with any 404(file not found) errors

DirectoryIndex index.php tells the default file in a directory is index.php, instead of others like index.html most of the time. So if a request doesn't specify the filename, index.php is called automatically.

RewriteEngine on: this one simply turns on the rewrite engine. You must ensure that you enable Apache's rewrite mode

RewriteCond %{REQUEST_FILENAME} !-f tells if a request is trying to access a file, don't follow the rewrite rule. Otherwise any requests to images, css, javascripts would be routed through index.php as well, which is not we expect.

RewriteCond %{REQUEST_FILENAME} !-d tells if q request is trying to access a directory that exists, don't follow the rewrite rule.

RewriteRule ^(.*)$ index.php/$1 is our final rewrite rule. We take everything(^(.*)$) from the URL except the domain name and append it to the index.php(index.php/$1). So if a URL is like 'http://domain.com/user/login/?username=test&password=test', the URL will be rewrited to 'http://domain.com/index.php/user/login/?username=test&password=test'

No comments: