lighttpd, php and clean urls

Here’s a situation, You have php running on a lighttpd server via fastcgi and you want clean urls (ie. /post/123/postname).

The typical way to-do this with lighttpd is to set the error-handler to your script.

$HTTP["host"] == "my.com" {
    server.document-root = "/var/www/my.com"
    server.error-handler-404 = "/index.php"
}

We use an error-handler here rather than rewriting the url as with apache because there’s no way to detect if the url is actually a file (ie. your css/js files).

Problem here is that this will break query strings for anything other than the root url (query strings are what’s after the ?). ie. when accessing /post/123/postname/?confirm=true the confirm will not appear in the $_GET or $_REQUEST arrays while /?confirm=true will.

So how do we fix this? The method I’ve used is to manually parse the query string and put its values into the get and request arrays, as below.

function fix_query_string()
{
    $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    $query = parse_url($url,PHP_URL_QUERY);
    if ($query == False || empty($query))
        return;
    $_SERVER['QUERY_STRING'] = $query;
    parse_str($query,$query);
    foreach($query as $key=>$value)
    {
        $_GET[$key] = $_REQUEST[$key] = $value;
    }
}
if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false)
    fix_query_string();

Hope this helps!

Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *