Kohana & Lighttpd: A quick way of doing pretty URL’s

Please note, this is hardly the best way of working - all requests to the path will be forced through PHP. This sucks performance wise for images and other static files.

However, by default unless you use mod_magnet there is no current support for the Apache:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

The above adds conditions to a rewrite rule, making sure that the request does not match a file or directory. Anyway - the simple solution for us Lighty users is to pipe everything through the Kohana index.php file. This is done by adding the following code into your lighttpd config file:

url.rewrite-once = (”^/k/(.*)$” => “k/index.php/$1″)

Hopefully obviously, if your Kohana app runs under the directory “russell”, you would alter the above to:

url.rewrite-once = (”^/russell/(.*)$” => “russell/index.php/$1″)

Or just running in the root?

url.rewrite-once = (”^/(.*)$” => “index.php/$1″)

In your index.php file, add the following after the first comment:

if (file_exists($_SERVER['ORIG_PATH_TRANSLATED'])) {
header(’X-Sendfile: ‘.$_SERVER['ORIG_PATH_TRANSLATED']);
exit();
}

This instructs PHP to check if the file already exists on the system, and then to get Lighttpd to send it directly - PHP should be running for a very short time. FYI, you will need to enable “allow-x-send-file” in your FastCGI config, or change the header line to use readfile instead.

When I’m finished testing Kohana, I’ll write a new post explaining how to use mod_magnet to do it better.

NB: For more information on Kohana, see their website and docs. Lighttpd also has some excellent documentation - especially on mod_rewrite.


About this entry