在Nginx反向代理配置中,基于访问控制列表(ACL)可以实现精细化的流量控制和安全防护。ACL允许您根据客户端IP、请求头、URI等多种条件来限制或允许访问。
location / {
# 允许特定IP或IP段
allow 192.168.1.0/24;
allow 10.0.0.1;
# 拒绝其他所有IP
deny all;
proxy_pass http://backend;
}
使用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;
}
proxy_pass http://backend;
}
}
}
location / {
# 检查特定的请求头
if ($http_user_agent ~* (bot|crawler|spider)) {
return 403;
}
# 检查Referer头
if ($http_referer !~* ^https://example\.com) {
return 403;
}
proxy_pass http://backend;
}
location ~ ^/admin {
# 只允许内部网络访问管理界面
allow 192.168.1.0/24;
deny all;
proxy_pass http://backend;
}
map $time_iso8601 $allowed_time {
default 0;
"~^2023-01-01T" 1; # 特定日期
"~^T(08|09|10|11|12|13|14|15|16|17):" 1; # 工作时间
}
server {
location / {
if ($allowed_time = 0) {
return 403 "Service unavailable outside working hours";
}
proxy_pass http://backend;
}
}
location / {
# 允许来自特定IP或带有特定token的请求
set $allow_access 0;
if ($remote_addr ~ ^192\.168\.1\.) {
set $allow_access 1;
}
if ($http_x_access_token = "SECRET_TOKEN") {
set $allow_access 1;
}
if ($allow_access = 0) {
return 403;
}
proxy_pass http://backend;
}
http {
# 定义ACL文件路径
include /etc/nginx/acl/ip_whitelist.conf;
server {
location / {
# 使用外部文件中定义的变量
if ($whitelisted_ip = 0) {
return 403;
}
proxy_pass http://backend;
}
}
}
/etc/nginx/acl/ip_whitelist.conf
内容示例:
geo $whitelisted_ip {
default 0;
192.168.1.0/24 1;
10.0.0.1 1;
}
$remote_addr
记录客户端IPreturn 200
代替return 403
来验证规则location / {
add_header X-ACL-Decision "Allowed from $remote_addr";
# 测试规则
# return 200 "ACL test passed for $remote_addr";
# 实际规则
allow 192.168.1.0/24;
deny all;
proxy_pass http://backend;
}
通过合理配置Nginx的ACL功能,您可以有效控制反向代理的访问权限,提高系统的安全性。