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"
    )
}

3 Responses to “Force or Prevent WWW subdomain with lighttpd”

  1. You forgot to escape the dots in the hosts.

    Reply
  2. Hi, im having the exact problem, had some problem at beggining and google created infinite number of links to my website, such as:
    http://www.www.firsatpedia.com ,www.x.xx.firsatpedia.com and so on.
    I used colonical later but problem and crawling still occurs, how can I just not respond those sub domains?
    I used ur above code without deleting old one but it produced some weird redirctions.
    http://www.firsatpedia.com

    # firsatpedia
    $HTTP["host"] =~ "(^|\.)firsatpedia\.com$" {
        fastcgi.server = (
            "/django.fcgi" => (
                "main" => (
                    "socket" => env.HOME + "/firsatpedia/firsatpedia.sock",
                    "check-local" => "disable",
                )
            ),
        )
        alias.url = (
            "/media" => env.HOME + "/firsatpedia/firsatpedia/media",
            "/static" => env.HOME + "/firsatpedia/firsatpedia/static",
        )
    
        url.rewrite-once = (
            "^(/media.*)$" => "$1",
            "^(/static.*)$" => "$1",
            "^/favicon\.ico$" => "/media/favicon.ico",
            "^(/.*)$" => "/django.fcgi$1",
        )
    }
    Reply
    • Perhaps try something like this:

      $HTTP["host"] =~ "^(www\.)?firsatpedia\.com$" {

      Notice the caret (^) at the beginning, which matches from the beginning of the host string. Your example was missing it, and was saying, match from either the beginning of the string or from a period.

      Reply

Comment

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>