-1

I have the following server block in Nginx config:

server {
    listen 80;
    listen 443 ssl;
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;

    server_name _;

    if ($scheme = http) {
       return 302 https://$host$request_uri;
    }

    location / {
        root /frontend/master;
        index index.html;
        try_files $uri $uri/ /index.html?$query_string;
    }
}

So I already have redirect from http to https. But how to do redirect from www.example.com to example.com for this rule?

UPD: the most important thing here is that domains in our service are dynamic, our users register them by themselves and then chaining them via DNS settings. So I need to make a redirect to non-www without putting some domains in the server_name variable.

Alexxosipov
  • 1,215
  • 4
  • 19
  • 45
  • 1
    Does this answer your question? [Nginx no-www to www and www to no-www](https://stackoverflow.com/questions/7947030/nginx-no-www-to-www-and-www-to-no-www) – Rob Dec 16 '20 at 12:14
  • You'll need a seperate server block with a 'server_name' including www. Then, redirect to non-www. [Nginx Redirect HTTP to HTTPS and WWW to Non-WWW](https://stackoverflow.com/questions/33047999/nginx-redirect-http-to-https-and-www-to-non-www) – 0stone0 Dec 16 '20 at 12:14
  • @Rob @0stone0 guys, the most important thing here that domains in our project's business logic are dynamic, so our clients can register their own domain to chain it with out service via DNS. So I can't just put domain in the `server_name` variable in the config. – Alexxosipov Dec 16 '20 at 12:20

1 Answers1

0

Try this

server_name ~^(www\.)?(?<hostname>.+)\.(?<zone>.+)$;

return 301 https://$hostname.$zone$request_uri;

You can change regexp with your hostname for example

YuriB.
  • 46
  • 1