I have a little problem with nginx. We have two subdomains we own, let's call them domain1.com and domain2.com. For domain2 we don't have further subdomains, for domain1 we have several. If someone enters www.domain2.com I would like nginx to forward the person to https://domain2.com
, otherwise just forward them to https://. I achieve this with these two blocks at the end of the config of domain2 in sites-available:
server {
listen 80;
server_name domain2.com;
return 301 https://$http_host$request_uri;
}
server {
listen 80;
server_name www.domain2.com;
return 301 https://domain2.com$request_uri;
}
Also I have HSTS enabled for all subdomains with add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload" always;
Now when navigating to www.domain2.com, browsers throw errors, because nginx presents them with the certificate of a_subdomain.domain1.com. This doesn't happen when directly accessing domain2.com, then nginx presents the correct certificate. And no, reverse proxying the subdomains of domain1 sadly is no option, nginx seems to have trouble with this in combination with PHP.
How do I make nginx to do this right?
Interestingly enough, I also have a config forwarding from a domain we used to host (different from domain1 and domain2) to the new domain on other servers, these forwardings don't have this issue, but the new page probably doesn't use HSTS, so that might be the reason.