可以使用 $http_user_agent 变量来判断用户代理,然后在 server 块中使用 map 指令将特定的用户代理映射为变量,最后在 location 块中使用 if 指令判断变量的值来限制访问。

例如,假设有两个域名 example.com 和 test.com,需要限制 test.com 只允许特定的用户代理访问,可以这样配置:

map $http_user_agent $is_allowed {
    default 0;
    ~*bot 1;
    ~*spider 1;
}

server {
    listen 80;
    server_name example.com;
    # 配置 example.com 的相关内容
}

server {
    listen 80;
    server_name test.com;
    if ($is_allowed = 0) {
        return 403;
    }
    # 配置 test.com 的相关内容
}

上述配置中,map 指令将用户代理匹配为 $is_allowed 变量,如果是 bot 或 spider,则为 1,否则为 0。在 test.com 的 server 块中,使用 if 指令判断 $is_allowed 的值,如果为 0,则返回 403 禁止访问。注意,这里使用了正则表达式匹配,需要在正则表达式前面加上 ~* 表示不区分大小写。

Nginx 限制特定域名访问 - 使用 User Agent 限制访问

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

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