0

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
}
Humberto Castellon
  • 849
  • 1
  • 7
  • 17
Microcipcip
  • 103
  • 1
  • 3
  • 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 Answers1

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.example.com;
        return 301 $scheme://example.com$request_uri;
    }

    server {

        listen 443;
        server_name example.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.example.com example.com;
        return 301 https://example.com$request_uri;
    }
Kernelv5
  • 187
  • 6