Setting up NGNIX to redirect from non-www to www

August 16, 2016 913 views
Nginx Node.js Ubuntu

Can anyone help me set-up the non- www to www redirection?

I 've tried Several tutorials here and not works, my nginx is:

server {
listen 80;

server_name mydomain.com;

location / {
    proxy_pass MY_IP_SERVER:8080;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

}

2 Answers
MDS August 16, 2016
Accepted Answer

The recommended way to do this is:

server {
    listen       80;
    server_name  example.org;
    return       301 http://www.example.org$request_uri;
}

server {
    listen       80;
    server_name  www.example.org;

    location / {
        proxy_pass MY_IP_SERVER:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

Replace example.org with your domain name.

And if anyone needs it, we've built a docker image to do just the non-www-to-www-redirect: https://hub.docker.com/r/webhare/www-redirector/

Have another answer? Share your knowledge.