I have multiple domains on a single host, and nginx manages all of them. Each domain has it's own SSL certificate (which I get from certbot, using the "webroot" plugin).
I have a server block at the end of each config file, as a "catch-all" (from here and here), to return 404 for invalid subdomains.
Default nginx config file default.conf
:
# ...other config...
include /path/to/domain1.conf;
include /path/to/domain2.conf;
# ...other config...
domain1.conf
:
# redirect http to https
server {
listen 80;
listen [::]:80;
server_name domain1.com www.domain1.com
return 301 https://$host$request_uri;
}
# redirect naked to www
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name domain1.com
include path/to/ssl_config.conf
return 301 https://www.$host$request_uri;
}
# serve subdomain www
server {
listen 443 ssl http2;
listen [::]443 ssl http2;
server_name www.domain1.com
include path/to/ssl_config.conf
location / { proxy_pass http://$app; }
}
# catch-all for invalid subdomains (e.g. foo.domain1.com)
server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
server_name: _.domain1.com
include path/to/ssl_config.conf
return 404;
}
domain2.conf
:
# same as above, but uses "domain2.com" instead of "domain1.com"
But that causes an error:
[emerg] a duplicate default server for xxx.xxx.xxx.xxx:443
If I remove those default_server
directives, then it doesn't route properly: a request to foo.example1.com
redirects to www.foo.example1.com
, then to www.www.foo.example1.com
, etc.
Everything works, except for the invalid subdomain logic. How can I fix it?