Archive for September 3rd, 2007


I am on Planet SysAdmin :)

It may be old news, but I have just found out (late as always :P). This blog was added to Planet SysAdmin list of blogs. Woohoo! ;) Seems that someone is reading this after all. :)


Playing with lighttpd

Apache mod_rewrite is a very powerful tool used in hundreds of web applications for various purposes, most notably for SEO friendly (or user friendly :)) URLs. Lighttpd also has mod_rewrite but some of the most important functionalities can be achieved using mod_redirect and mod_magnet.

mod_redirect does exactly what its name says – it will redirect visitor from matched URL to a desired URL. One of the cases when this is very useful is redirecting visitors who were too lazy to type ‘www’ part of your web site address to a proper address. In Apache you would use mod_rewrite with a similar syntax.

RewriteCond %{HTTP_HOST} ^miljan\.org$ [NC]
RewriteRule ^(.*)$$1 [R=301,L]

In lighttpd you can use mod_redirect with the following syntax:

$HTTP["host"] =~ “^miljan\.org” {
    url.redirect = (
        ”^/(.*)$” => “$1″

As you can see regular expressions in Apache and lighttpd are the same. Only difference is in configuration syntax.

mod_redirect can be used also for simple redirections:

url.redirect = (
    ”^/main/gallery” => “”,
    ”^/main/travelblog” => “”,
    ”^/main/tips-n-tricks” => “”

In Apache, this would look like:

Redirect permanent /main/gallery
Redirect permanent /main/travelblog
Redirect permanent /main/tips-n-tricks

Note: you need mod_alias in order to use Redirect directive.

Now, SEO URLs. Standard way of doing this with Apache and mod_rewrite is:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /index.php [L]

Basically, it will check if the filename/folder requested exists on the filesystem and if not all requests will be transfered to a desired file (index.php in this case). It works pretty much as a 404 error page.

Lighttpd does this also in a similar way. It is only necessary to set a 404 error page and it will work. But for some reason this doesn’t work for me. It might be due to a bug in server.error-handler-404 (lighttpd 1.4.17 was released 5 days ago with this bug fixed). But there is a workaround for this. Lighttpd has mod_magnet which uses capabilities of LUA script language – so we can use a small LUA script to check if the file/folders exists and if not to transfer all requests to index.php file.

First we setup lighttpd:

$HTTP["url"] =~ “^.*(html|php|/).*$” {
    magnet.attract-physical-path-to = (“/etc/lighttpd/magnet-rewrite.lua”)

Than we create /etc/lighttpd/magnet-rewrite.lua script:

if (not lighty.stat(lighty.env["physical.path"])) then
    lighty.env["physical.path"] = lighty.env["physical.doc-root"] .. “/index.php”

And that is all. Not as simple as Apache, and not even close as simple as setting up a 404 page in lighttpd, but it works!