0

This question already has an answer here:

I am trying to redirect HTTPS www request to non-www but I can't get it to work. What line of code would I have to change to achieve the redirection?

server {
    root /var/www/mydomain.com/html;
    index index.html index.htm index.nginx-debian.html;

    server_name mydomain.com www.mydomain.com;

    #gZip stuff here...
    #Certbot stuff here...
}

server {
    if ($host = www.mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    listen [::]:80;

    server_name mydomain.com www.mydomain.com;
    return 404; # managed by Certbot
}

marked as duplicate by Richard Smith, Thomas, Ward Nov 30 '18 at 18:08

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • I've not tested this, but I think your 301 redirects must be in the first server block that contains server_name. Your non-www domain must be the first server_name, as already is. – digijay Nov 13 '18 at 21:01
  • Oh wait, I didn't scroll down enough, why is server_name featured there a second time? I would rather make it one block. – digijay Nov 13 '18 at 21:04
  • The second block was created by certbot, how do I combine them? – Microcipcip Nov 13 '18 at 23:14
1

I recommend managing mention below way. As per Nginx Documentation, it's their recommended way also to handle domain level redirection.

server {

        listen 443; 
        server_name www.mydomain.com;
        return 301 $scheme://example.com$request_uri;
    }

    server {

        listen 443;
        server_name mydomain.com;

         root /var/www/mydomain.com/html;
         index index.html index.htm index.nginx-debian.html;

        # Others Configuration...

    }

If you want you can also add one more server block to redirect HTTP to https.

server {

        listen 80;
        server_name www.mydomain.com mydomain.com;
        return 301 https://example.com$request_uri;
    }
  • I copied to the first server block all Certbot code and it worked, but I had to remove this line listen [::]:443 ssl; and just leave listen 443 ssl; – Microcipcip Nov 14 '18 at 9:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.