Nginx 域名特定 UA 访问限制 (无需 if 语句)
可以使用 Nginx 的 map 模块和 geo 模块来实现特定域名仅允许特定 UA 访问。
首先,在 nginx.conf 配置文件中定义一个 map,将需要限制 UA 的域名映射到一个变量中:
map $host $allowed_ua {
default "";
example.com 'Googlebot|Bingbot';
}
在上面的例子中,只有 example.com 这个域名需要限制 UA,只允许 Googlebot 和 Bingbot 访问。其他域名则没有限制。
接下来,在 http 或 server 块中使用 geo 模块,将需要限制 UA 的 IP 地址映射到一个变量中:
geo $limited_ua {
default 0;
127.0.0.1 1;
}
在上面的例子中,127.0.0.1 这个 IP 地址需要限制 UA。如果来自该 IP 地址的请求的 UA 不在 allowed_ua 变量中定义的范围内,则不允许访问。
最后,在 server 或 location 块中使用 if 语句来对需要限制 UA 的域名和 IP 地址进行判断:
if ($allowed_ua != "" && $limited_ua = 1) {
if ($http_user_agent !~ $allowed_ua) {
return 403;
}
}
在上面的例子中,如果 allowed_ua 变量不为空且 limited_ua 变量等于 1,则判断请求的 UA 是否在 allowed_ua 变量中定义的范围内。如果不在,则返回 403 错误。
需要注意的是,if 语句在 Nginx 中的性能不是很好,建议尽量避免使用。如果需要更高效的方式来限制 UA,可以考虑使用 Lua 脚本或者自定义模块。
原文地址: http://www.cveoy.top/t/topic/nUSr 著作权归作者所有。请勿转载和采集!