The http
server does not require a specific certificate, so all domains can be redirected to https
non-www with a single server
block.
For example:
server {
listen 80;
server_name ~^(www\.)?(?<domain>.+)$;
return 301 https://$domain$request_uri;
}
See this document for more.
The https
servers probably require a specific certificate for each domain. To redirect from www to non-www, a specific certificate should be valid for both name variants. You should use two server
blocks for each specific domain, the existing one and another to perform the redirect.
For example:
server {
listen 443 ssl;
server_name www.example.com;
ssl_certificate /path/to/example.com.crt;
ssl_certificate_key /path/to/example.com.key;
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/example.com.crt;
ssl_certificate_key /path/to/example.com.key;
... this is the existing server block for this domain ...
}
See this document for more.