Home > Blockchain >  How to redirect www to non-www in nginx
How to redirect www to non-www in nginx

Time:12-12

This is my current nginx config:

server {
        server_name mydomain.com www.mydomain.com;

        listen 443 ssl;
        ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem;
        include /etc/letsencrypt/options-ssl-nginx.conf;
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}

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

        if ($host = mydomain.com) {
            return 301 https://$host$return_uri;
        }

        server_name mydomain.com www.mydomain.com
        listen 80;
        return 404;
}

This works fine but I need to redirect www to non-www too. How to do that?

CodePudding user response:

Try this:

location / {
  if ($http_host ~* "^www.example.com"){
    rewrite ^(.*)$ https://example.com/$1 redirect;
  }
}
  • Related