在Nginx反向代理配置中,基于客户端IP地址进行访问控制(ACL)是一项常见的安全需求。以下是几种实现方式:
allow
和deny
指令location / {
deny 192.168.1.1; # 拒绝特定IP
allow 192.168.1.0/24; # 允许特定子网
allow 10.1.1.0/16; # 允许另一个子网
deny all; # 拒绝所有其他IP
proxy_pass http://backend;
}
geo
模块创建IP分组geo $acl {
default 0;
192.168.1.0/24 1;
10.0.0.0/8 1;
172.16.0.0/12 1;
}
server {
location / {
if ($acl = 0) {
return 403; # 禁止访问
}
proxy_pass http://backend;
}
}
map
模块的复杂ACLmap $remote_addr $acl {
default "deny";
"192.168.1.100" "allow";
"10.0.0.0/8" "allow";
}
server {
location / {
if ($acl = "deny") {
return 403;
}
proxy_pass http://backend;
}
}
当Nginx前面还有代理层时,需要检查X-Forwarded-For头:
# 提取真实客户端IP
map $http_x_forwarded_for $real_ip {
default $remote_addr;
~^([^,]+) $1;
}
geo $acl {
default 0;
192.168.1.0/24 1;
include /etc/nginx/conf.d/ip_whitelist.conf;
}
server {
location / {
if ($acl = 0) {
return 403;
}
proxy_pass http://backend;
}
}
对于基于地理位置的ACL:
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;
}
}
}
# /etc/nginx/conf.d/acl.conf
geo $acl {
default 0;
include /etc/nginx/conf.d/ip_whitelist.conf;
}
# /etc/nginx/conf.d/ip_whitelist.conf
192.168.1.0/24 1;
10.0.0.0/8 1;
# nginx server配置
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
location / {
if ($acl = 0) {
access_log /var/log/nginx/denied.log;
return 403;
}
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://backend_servers;
}
}
通过以上配置,您可以灵活地实现基于IP地址的访问控制,保护您的反向代理服务。