Score:0

Nginx, unable to redirect www domain to https non www domain when using certbot

us flag

Despite being there a lot of examples online I have tried a lot of stuff, specifically using if statements, but so far ive been unable to setup my vhost properly

So my vhost is

    a1.example.com

www.a1.example.com should redirect to https://a1.example.com
a1.example.com should redirect to https://a1.example.com

The goal is to redirect it to https non-www every single time.

This is my vhost so far, im using certbot

server {
     server_name a1.example.com www.a1.example.com;
     root /var/www/example/build;

     index index.html index.htm;

     location / {
          try_files $uri $uri/ =404;
     }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/a1.example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/a1.example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {

    if ($host = a1.example.com) {

    return 301 https://$host$request_uri;
   }
     listen 80;
     listen [::]:80;
     server_name a1.example.com www.a1.example.com;
    return 404; # managed by Certbot

}

This does redirect from http to https, but im unable to do the redirect www to nonwww

My current dns records are

A @ IP
A a1 IP
CNAME www domain
CNAME www.a1 www.a1.domain
Ivan Shatsky avatar
gr flag
Please take an attention I missed question sign in regex (`^(?:www\.)a1\.example\.com$` instead of `^(?:www\.)?a1\.example\.com$`). I have already corrected the answer.
Score:1
gr flag

I think the best answer on this subject was given by @MichaelHampton here. As a quick fix you can add

if ($host = www.a1.example.com) {
    return 301 https://a1.example.com$request_uri;
}

to your HTTPS server block and change if ($host = a1.example.com) { ... } in HTTP server block to

if ($host ~ ^(?:www\.)?a1\.example\.com$) {
    return 301 https://a1.example.com$request_uri;
}

Anyway I totally agree with Michael Hampton that you shouldn't allow certbot to alter your nginx configuration and use it only for getting/renewing certificates (see his answer for well written nginx config example).

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.