Nginx 限制特定域名访问:使用 map 指令和变量
可以使用 map 指令和一个变量来实现。
- 在 http 块下定义一个 map,把需要限制 UA 的域名和 UA 列表对应起来:
http {
map $host $ua_allowed {
'example.com' 1;
'example2.com' 0;
}
...
}
在上面的例子中,'example.com' 允许特定 UA 访问,而 'example2.com' 则不允许。
- 在 server 块中使用这个变量来控制访问:
server {
server_name 'example.com' 'example2.com';
...
if ($ua_allowed = 0) {
return 403;
}
...
}
在上面的例子中,如果 $ua_allowed 变量的值为 0,则返回 403 Forbidden,否则允许访问。
注意:if 语句在 nginx 中的使用是有限制的,尽量不要使用 if 语句。
原文地址: http://www.cveoy.top/t/topic/nUSk 著作权归作者所有。请勿转载和采集!