Configure nginx with certbot for www and non-www

Hi. I can’t get my nginx server to work with Let’s Encrypt (Certbot) for both www and non-www. This is my current sites-enabled:

server {
root …
index …
server_name www.domain.com
listen 443 ssl;
ssl_certificate …
ssl_certificate_key …
include …
ssl_dhparam …
}

server {
if ($host = www.domain.com {
return 301 https://$host$request_uri;
}

listen 80;
server_name domain.com www.domain.com;
return 301 https://www.domain.com$request_uri;

}

server {
listen 443;
server_name www.domain.com
return 301 https://www.domain.com$request_uri;

}

Now, what happens is that it works with www, but not without. Where am I fucking this up?

Hi @mattisern,

What you want to do?. Redirect http domain & www.domain & https domain to https www.domain?

Cheers,
sahsanu

Well, just in case, this is the skeleton to redirect http domain & www.domain & https domain to https www.domain.

server {
    listen 80;
    server_name domain.tld www.domain.tld;
    return 301 https://www.domain.tld$request_uri;
}

server {
    listen 443 ssl;
    server_name domain.tld;
    ssl_certificate /etc/letsencrypt/live/domain.tld/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/domain.tld/privkey.pem;
    #other ssl options
    return 301 https://www.domain.tld$request_uri;
}

server {
    listen 443 ssl;
    server_name www.domain.tld;
    #your root, index, etc. stuff
    ssl_certificate /etc/letsencrypt/live/domain.tld/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/domain.tld/privkey.pem;
    #other ssl options
}

Note: in the example, domain.tld & www.domain.tld are both covered by the same certificate which is located in /etc/letsencrypt/live/domain.tld/, keep that in mind because if you have one certificate covering only domain.tld and another one covering www.domain.tld then the paths should be replaced in the example with the right ones.

Hope this helps.

Cheers,
sahsanu

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.