Nginx 允许通过域但不允许通过 IP [英] Nginx allow via Domain but not via the IP

查看:50
本文介绍了Nginx 允许通过域但不允许通过 IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的配置:

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";
    ...
}

我想要实现的是通过 IP 阻止访问.并且只允许通过域.

What I am trying to achieve is block access via the IP. And only allow it via the domain.

我见过一些使用正则表达式的解决方案,但我同时使用 IPv4 和 IPv6.而且它不应该影响性能.

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?

推荐答案

您需要定义一个捕获所有服务器.在 listen 指令中使用 default_server 参数.

You need to define a catch all server. Use the default_server parameter on the listen directive.

例如:

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;
}

服务器需要一个证书来阻止 https 连接,任何证书都可以.客户端的浏览器会发出警告,但无论如何他们都不应该尝试连接到没有正确域名的安全服务器.

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.

server_name 指令不是必需的.非标准代码 444 关闭连接而不发送响应头.

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.

这篇关于Nginx 允许通过域但不允许通过 IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆