Nginx 域名 UA 限制 - 使用 Map 模块实现特定域名 UA 只能带 qyuc 访问
可以使用 map 模块来实现特定域名 UA 只能带 'qyuc' 才能访问的配置,具体配置如下:
- 在 http 块中定义一个 map 变量,用来存储特定域名对应的 UA 白名单:
http {
map $host $ua_whitelist {
default 0;
example.com 'qyuc';
test.com 'qyuc';
}
...
}
- 在 server 块中使用变量判断请求的域名和 UA 是否满足条件:
server {
listen 80;
server_name example.com test.com;
if ($ua_whitelist = 0) {
return 403;
}
location / {
...
}
}
- 使用 if 语句判断请求的 UA 是否符合条件,如果符合则将变量设置为 1,否则设置为 0:
http {
map $host $ua_whitelist {
default 0;
example.com 'qyuc';
test.com 'qyuc';
}
server {
listen 80;
server_name example.com test.com;
if ($http_user_agent ~* "qyuc") {
set $ua_whitelist 1;
}
else {
set $ua_whitelist 0;
}
if ($ua_whitelist = 0) {
return 403;
}
location / {
...
}
}
...
}
- 使用 geo 模块和 map 模块结合,可以更灵活地进行特定区域和特定域名的限制:
http {
geo $region {
default unknown;
CN china;
US usa;
}
map $host$region $ua_whitelist {
default 0;
example.comchina 'qyuc';
test.comusa 'qyuc';
}
server {
listen 80;
server_name example.com test.com;
if ($http_user_agent ~* "qyuc") {
set $ua_whitelist 1;
}
else {
set $ua_whitelist 0;
}
if ($ua_whitelist = 0) {
return 403;
}
location / {
...
}
}
...
}
以上是使用 map 模块实现特定域名 UA 只能带 'qyuc' 才能访问的配置方法,避免了使用 if 语句对性能的影响。
原文地址: https://www.cveoy.top/t/topic/nwAP 著作权归作者所有。请勿转载和采集!