问题
This is my configuration:
server {
listen 80;
listen [::]:80;
server_name domain.tld www.domain.tld;
return 301 https://erp.uni.mk$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name domain.tld;
ssl_certificate "/etc/nginx/ssl/ca_full.crt";
ssl_certificate_key "/etc/nginx/ssl/private.key";
...
}
What I am trying to achieve is block access via the IP. And only allow it via the domain.
I've seen some solutions with regex, but I am using both IPv4 and IPv6. And it should not impact performance.
Any suggestions how to solve this?
回答1:
You need to define a catch all server. Use the default_server parameter on the listen directive.
For example:
server {
listen 80 default_server;
listen 443 ssl default_server;
ssl_certificate /path/to/any/cert.pem;
ssl_certificate_key /path/to/any/key.pem;
return 444;
}
The server needs a certificate to block https connections, any certificate will do. The client's browser will throw warnings, but they shouldn't be trying to connect to a secure server without a correct domain name anyway.
The server_name directive is not required. The non-standard code 444 closes the connection without sending a response header.
See this document for details.
来源:https://stackoverflow.com/questions/61800208/nginx-allow-via-domain-but-not-via-the-ip