Lighttpd Redirect to SSL results in 301 redirect loop

301-redirecthttpslighttpd

I am running lighttpd 1.4.31 with ssl support and am having an issue with forcing https on a specific virtualhost. If I disable the redirect line from the following config, it works as expect (http and https both working, but no redirection), but when I enable it, I find the browser gets cause in a loop of 301s. I don't understand why this is happening as to me the redirect should only apply under http. I have mod_redirect loaded in at the top of the config, and one other virtualhost with ssl forced on for some domain…I don't believe that should have any impact. What am I doing wrong in the following config snippet? Please note that I substituted site.example.com for my domain.

$HTTP["host"] == "site.example.com" {
    dir-listing.activate = "enable"
    accesslog.filename = "/home/lighttpd/site.example.com/logs/access.log"
    server.document-root = "/home/lighttpd/site.example.com/htdocs"
    server.upload-dirs = ("/tmp")
    server.errorlog = "/home/lighttpd/site.example.com/logs/error.log"
    $SERVER["socket"] == ":443" {
            ssl.engine = "enable"
            ssl.pemfile = "/home/lighttpd/site.example.com/cert.pem"

            $HTTP["url"] =~ "^/shell" { # shellinabox
                    proxy.server = ( "" => ((
                                    "host" => "127.0.0.1",
                                    "port" => 4200,
                                    ),),)
            }
    }
    $HTTP["scheme"] == "http" {
            url.redirect = (".*" => "https://site.example.com/$0")
    }
}

Best Answer

Taking a look at my configuration, which is almost the same as you:

  • I want https
  • and http redirect to https.

I have one more things inside my socket config:

$SERVER["socket"] == ":443" {
        ssl.engine  = "enable"

        # .....

        setenv.add-environment = (
                "HTTPS" => "on"
        )
}

And my redirect is handled outside the first host, like this:

$HTTP["scheme"] == "http" {
        $HTTP["host"] =~ "site.example.fr" {
                url.redirect = ( "^/(.*)" => "https://site.example.fr/$1" )
        }
}

And every thing works like a charm.