在Nginx中设置白名单可以通过多种方式实现,主要取决于你想要限制的内容类型(IP地址、域名、用户代理等)。以下是几种常见的白名单配置方法:
location / {
# 允许的IP列表
allow 192.168.1.1;
allow 192.168.1.2;
allow 10.0.0.0/8;
# 拒绝所有其他IP
deny all;
# 其他配置...
}
location / {
include /etc/nginx/whitelist-ips.conf;
deny all;
# 其他配置...
}
然后在/etc/nginx/whitelist-ips.conf
文件中:
allow 192.168.1.1;
allow 192.168.1.2;
location / {
valid_referers none blocked server_names
~.example.com
~.trusted-domain.com;
if ($invalid_referer) {
return 403;
}
# 其他配置...
}
location / {
if ($http_user_agent !~* "(Googlebot|Bingbot|YandexBot)") {
return 403;
}
# 其他配置...
}
首先确保安装了ngx_http_geoip_module
模块,然后:
http {
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default no;
US yes;
CA yes;
GB yes;
}
server {
location / {
if ($allowed_country = no) {
return 403;
}
# 其他配置...
}
}
}
location / {
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
# 其他配置...
}
nginx -t && nginx -s reload
需要针对特定场景的白名单配置建议,可以提供更多细节,我可以给出更具体的方案。