0

I'm having issues with a site that has a Let's Encrypt cert for the naked domain example.com. There is a CNAME DNS entry that points www to the A record.

I want all www traffic to redirect to the non-www version and all non-:443 traffic to redirect to :443.

Here is a representation of my config:

server {
    server_name  www.example.com;
    rewrite ^(.*) https://example.com$1 permanent;
}
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name _;

    location / {
       return 301 https://$host$request_uri;
    }
}

server {
    server_name example.com; # managed by Certbot

    location / {
        if ($request_method = 'GET') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        }

        proxy_pass http://127.0.0.1:8000;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_Addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }


    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    # relevant ssl cert info

}    

This setup is currently causing a certificate name mismatch for some cases where the user attempts to visit the www version of the site.

Based on what I have read so far, it would seem I need to add another server block to handle the :443 www redirect, which might look something like this:

server {
    listen 443 ssl;
    server_name www.example.com;
    rewrite ^(.*) https://example.com$1 permanent;
}    

Is this correct?

  • Where's the SSL cert info? And why didn't certbot add it in? – Michael Hampton Jan 23 at 0:58
  • Cerbot added the info correctly, I removed it for this example as it is not relevant. There's no issue with the cert itself, the problem relates to www redirect. – Chase Jan 23 at 1:03
  • Wait, didn't you create the certificate with both hostnames? – Michael Hampton Jan 23 at 1:04
  • No, just the naked domain. – Chase Jan 23 at 1:05
  • 1
    Yeah, that's probably the best thing to do. – Michael Hampton Jan 23 at 1:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.