0

Now the site works in both www and non www. I want it to work only in www and redirect all the non-www to www. Both for HTTP and HTTPS.

I have the following vhost:

server {
        listen 80;
        server_name example.com www.example.com;
        return 301 https://$host$request_uri;
}




server {
        listen 443 ssl;
        server_name example.com www.example.com;
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';


        location /  {
                proxy_pass    http://localhost:3006;
                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;
        }
}

I tried to change

return 301 https://$host$request_uri;

to

return 301 https://www.$host$request_uri;

But it doesn't work

I tried to change it to: return 301 https://www.example.com$request_uri;

But it also does not work. I hope someone knows and can help to make it work...

1 Answer 1

1

Your changing the wrong server block. The second server block contains:

server_name example.com www.example.com;

and needs to be split into two separate server blocks. You can then redirect from one to the other.

For example:

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}
server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate ...;
    ssl_certificate_key ...;
    return 301 https://www.$server_name$request_uri;
}
server {
    listen 443 ssl;
    server_name www.example.com;
    ssl_certificate ...;
    ssl_certificate_key ...;
    ...
    ...
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .