可以使用 nginx 的模块 'ngx_http_geo_module' 来实现限制特定 IP 访问域名。

首先在 nginx 的配置文件中定义一个 geo 区块,用于存储特定 ip 的信息:

geo $allowed_ips {
    default 0;
    10.0.0.1/24 1;
    192.168.1.1/32 1;
}

其中,$allowed_ips 是一个变量,存储的是 ip 地址和对应的值(1 表示允许访问,0 表示不允许访问)。在这个例子中,定义了两个 ip 地址允许访问。

为了避免使用 if 语句降低 nginx 的性能,可以使用 map 指令代替 if 语句:

map $allowed_ips $access {
    0 403;
    1 "";
}

server {
    listen 80;
    server_name example.com;

    location / {
        if ($access) {
            return $access;
        }
        # 其他配置
    }
}

这样,如果 $allowed_ips 的值为 0,则 $access 的值为 403,否则为空字符串。在 location 中,只需要判断 $access 是否为空字符串即可。这样就避免了 if 语句的使用,提高了 nginx 的性能。

Nginx 限制特定 IP 访问域名:高效配置方法

原文地址: http://www.cveoy.top/t/topic/nURl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录