Nginx提供了多种方式来实现IP地址访问控制,以下是几种常用的方法:
在Nginx配置文件中,可以使用allow
和deny
指令来控制IP访问:
location / {
# 允许特定IP
allow 192.168.1.1;
allow 192.168.1.2;
# 拒绝所有其他IP
deny all;
# 其他配置...
}
对于更复杂的IP控制,可以使用geo
模块:
geo $allowed_ip {
default 0;
192.168.1.0/24 1;
10.0.0.1 1;
}
server {
location / {
if ($allowed_ip = 0) {
return 403;
}
# 其他配置...
}
}
map
模块也可以用于IP控制:
map $remote_addr $is_allowed {
default 0;
192.168.1.1 1;
10.0.0.0/8 1;
}
server {
location / {
if ($is_allowed = 0) {
return 403;
}
# 其他配置...
}
}
可以结合HTTP基本认证和IP限制:
location /admin {
satisfy any;
allow 192.168.1.0/24;
deny all;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location ~* \.(php|log|conf)$ {
allow 192.168.1.100;
deny all;
}
对于大量IP地址,可以使用单独的文件:
include /etc/nginx/allowed_ips.conf;
然后在allowed_ips.conf
中:
allow 192.168.1.1;
allow 10.0.0.1;
# 更多IP...
deny all
通常放在最后nginx -s reload
http {
# 定义允许的IP范围
geo $blocked {
default 1;
192.168.1.0/24 0;
10.0.0.0/8 0;
}
server {
listen 80;
server_name example.com;
location / {
if ($blocked) {
return 403;
}
# 正常处理请求
root /var/www/html;
index index.html;
}
location /admin {
allow 192.168.1.100;
deny all;
# 其他配置...
}
}
}
以上方法可以根据实际需求组合使用,实现灵活的IP访问控制策略。