Nginx 使用 Map 模块限制特定 UA 访问 (无需 if 语句)
可以使用 map 模块和 $http_user_agent 变量来实现不使用 if 语句的限制特定 UA 访问的配置。具体步骤如下:
- 在 http 块中定义一个 map,将需要限制的 UA 映射为一个变量值,例如:
http {
map $http_user_agent $ua_allowed {
default 0;
~*bot 0;
~*spider 0;
~*crawler 0;
~*googlebot 1;
~*bingbot 1;
}
...
}
上述配置中,$ua_allowed 变量的默认值为 0,表示不允许访问;如果 UA 匹配到了 'bot'、'spider'、'crawler' 等关键词,则也不允许访问;但如果 UA 匹配到了 'googlebot' 或 'bingbot',则 $ua_allowed 变量的值为 1,表示允许访问。
- 在 server 块中设置限制访问的规则,例如:
server {
listen 80;
server_name example.com www.example.com;
if ($ua_allowed = 0) {
return 403;
}
...
}
上述配置中,如果 $ua_allowed 变量的值为 0,则返回 403 错误码,拒绝访问;否则可以正常访问。
通过使用 map 模块和 $http_user_agent 变量,可以实现不使用 if 语句的限制特定 UA 访问的配置,避免了 if 语句的性能问题和不稳定性。
原文地址: http://www.cveoy.top/t/topic/nUR0 著作权归作者所有。请勿转载和采集!