可以使用 map 指令来实现,具体步骤如下:

  1. 在 nginx 配置文件中添加一个 map 指令,用于匹配特定的 User-Agent,例如:
map $http_user_agent $is_allowed {
    default 0;
    ~*bot 0;
    ~*spider 0;
    ~*googlebot 1;
}

其中,$http_user_agent 是 nginx 内置的变量,表示请求头中的 User-Agent;$is_allowed 是自定义的变量,用于存储匹配结果;default 表示默认值为 0,即不允许访问;~*bot~*spider~*googlebot 是正则表达式,用于匹配 User-Agent 中包含这些字符串的请求,其中 ~* 表示不区分大小写。

  1. 在 server 段中添加两个 location 段,分别绑定两个域名,例如:
server {
    listen 80;
    server_name domain1.com;
    
    location / {
        if ($is_allowed = 0) {
            return 403;
        }
        # 其他配置
    }
}

server {
    listen 80;
    server_name domain2.com;
    
    location / {
        # 其他配置
    }
}

其中,第一个 location 段中使用 if 语句判断 $is_allowed 变量的值,如果为 0,则返回 403 状态码,否则允许访问;第二个 location 段中不做限制。

  1. 在请求头中添加 User-Agent 为测试,测试两个域名的访问情况,例如:
curl -H 'User-Agent: test' http://domain1.com

此时,访问 domain1.com 会返回 403 状态码,访问 domain2.com 则不受限制。如果 User-Agent 为 Googlebot,则可以访问 domain1.com。

Nginx 配置特定域名仅允许特定 User-Agent 访问 (无 if 语句)

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

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