Nginx可以通过多种方式实现基于客户端IP地址的访问控制,以下是几种常见的方法:
allow
和deny
指令这是最基础的IP访问控制方式,可以在http
、server
或location
块中使用:
location / {
# 允许特定IP
allow 192.168.1.1;
allow 10.0.0.0/24;
# 拒绝其他所有IP
deny all;
# 其他配置...
}
geo
模块geo
模块可以创建变量基于客户端IP地址:
http {
# 创建$allowed变量,默认为0(拒绝),特定IP为1(允许)
geo $allowed {
default 0;
192.168.1.1 1;
10.0.0.0/24 1;
}
server {
location / {
if ($allowed = 0) {
return 403;
}
# 其他配置...
}
}
}
map
模块类似于geo
,但更灵活:
http {
map $remote_addr $allowed {
default 0;
192.168.1.1 1;
10.0.0.0/24 1;
}
server {
location / {
if ($allowed = 0) {
return 403;
}
# 其他配置...
}
}
}
ngx_http_access_module
模块这是Nginx默认编译的模块,提供基本的访问控制功能:
location /admin {
# 只允许特定IP访问/admin路径
allow 192.168.1.100;
allow 10.0.0.0/24;
deny all;
# 其他配置...
}
当Nginx位于负载均衡器或CDN后面时:
location / {
# 从X-Forwarded-For获取真实IP
set $real_ip $remote_addr;
if ($http_x_forwarded_for ~ "^(\d+\.\d+\.\d+\.\d+)") {
set $real_ip $1;
}
# 基于真实IP进行控制
if ($real_ip !~ "^(192\.168\.1\.1|10\.0\.0\.\d+)$") {
return 403;
}
# 其他配置...
}
ngx_http_geoip_module
模块(需要安装)可以基于国家/地区进行访问控制:
http {
geoip_country /path/to/GeoIP.dat;
server {
location / {
if ($geoip_country_code != US) {
return 403;
}
# 其他配置...
}
}
}
allow
/deny
指令最为直接geo
或map
模块更易于维护# 在配置文件中
include /etc/nginx/conf.d/allowed_ips.conf;
# allowed_ips.conf内容
allow 192.168.1.1;
allow 10.0.0.0/24;
# ...
以上方法可以根据实际需求单独使用或组合使用,以实现灵活的IP访问控制策略。