Mattias Hising - Product and Web Developer

How to build profitable high performance web products that user loves

Redirect Www to Non-www on Nginx

Logging this as a note for myself (and eventually someone else) so I dont forget it. Solves the problem of coexisting contexts www and non-www. With this all requests to www.* are redirected to * on the nginx webserver

<code>server {

    listen 80;

    server_name www.domain.com domain.com;

    root /var/www/domain.com/public_html;

    index /index.html;

    if ($host = 'www.domain.com' ) {
        rewrite  ^/(.*)$  http://domain.com/$1  permanent;
    }

    location / {
        #whatever
    }

    location ~ /\.ht {
        deny  all;
    }
}</code>

Update. According to Nginx the above code is a common pitfall, and should instead read:

<code>server {
        server_name www.domain.com;
        rewrite ^ $scheme://domain.com$request_uri redirect;
}

server {

    listen 80;

    server_name domain.com;

    root /var/www/domain.com/public_html;

    index /index.html;

    location / {
        #whatever
    }

}</code>

There are actually three problems here. The first being the if. That’s what we care about now. Why is this bad? Did you read If is Evil? When nginx receives a request no matter what is the subdomain being requested, be it www.domain.com or just the plain domain.com this if directive is always evaluated. Since you’re requesting nginx to check for the Host header for every request. It’s extremely inefficient. You should avoid it. Instead use two server directives like the example below.

Thanks to Johan as well who pointed me in this direction in his comments. However, if you use the first setup, I dont think you have to hurry to change it, it is almost certain of academic value on 90%+ of all nginx-setups.