NGINX - Redirecting www to non-www after redirecting http to https

I've checked out quite a few other answers to similar questions as well as tutorials on DigitalOcean, etc., with no success. Sorry for what is probably a very obvious problem - I'm new to this.

Essentially, I need to set up redirects so that http://, https://www., and http://www. all redirect to https://.

Currently, https:// works fine and http:// redirects to https://. I need to redirect www traffic because the SSL cert is only configured for non-www. However, when I've tried to add another server block to the config to redirect www (http and https) to https://, the server closes the connection on all 4 variants.

Here's my config:

# HTTP - redirect to HTTPS
server {
    listen 80;
    server_name www.example.com example.com;
    return 301 https://example.com$request_uri;
}

# HTTPS www - redirect to non-www RESETS CONNECTION
#server {
#    listen 443;
#    server_name www.example.com;
#    return 301 https://example.com$request_uri;
#}


# HTTPS — proxy all requests to the Node app
server {
    # Enable HTTP/2
    listen 443 ssl http2;
    server_name example.com;

    # Use the Let’s Encrypt certificates
    ssl_certificate /etc/not/my/path/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/not/my/path/live/example.com/privkey.pem;

    # Include the SSL configuration from cipherli.st
    include snippets/ssl-params.conf;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://0.0.0.0:2368/;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
    }
}

Can anyone tell me what I'm doing wrong? Again I know it's probably painfully obvious but I just can't get this to work. Should I be doing this with something other than an NGINX redirect?


Solution 1:

You cannot redirect www.example.com https traffic to example.com, unless you have the certificate for www.example.com. SSL negotiation uses domain name, and redirection happens only after SSL layer has been negotiated.