Force or Prevent WWW subdomain with lighttpd

Add one of the following lines to /etc/lighttpd/lighttpd.conf to either prevent the www subdomain or force it. You'll need to change the code to use your domain name, of course. The redirect will preserve the page the user was visiting, e.g. the /blog/post/200 will be appended to the target domain.

Why would someone want to prevent or force the subdomain? Well, if someone logs into your website using one domain, their cookie's might not be available on the other. Also, having the same pages accessible with two different URLs can ding you in SEO points (unless you use the canonical tag). If someone loads a resource on one of the domains (such as an image), it will need to be re-downloaded on the other domain.

# Disable WWW Subdomain
$HTTP["host"] =~ "^www.(.*)" {
    url.redirect = (
        "^/(.*)" => "http://%1/$1"
    )
}

# Force WWW Subdomain
$HTTP["host"] =~ "^example.com$" {
    url.redirect = (
        "^/(.*)" => "http://www.example.com/$1"
    )
}
Thomas Hunter II Avatar

Thomas is the author of Advanced Microservices and is a prolific public speaker with a passion for reducing complex problems into simple language and diagrams. His career includes working at Fortune 50's in the Midwest, co-founding a successful startup, and everything in between.