Nginx提供了多种方式来实现基于IP地址的访问控制,以下是几种常见的方法:
在Nginx配置文件中,可以使用allow
和deny
指令来控制IP访问:
location / {
# 允许特定IP
allow 192.168.1.100;
allow 10.0.0.0/8;
# 拒绝其他所有IP
deny all;
# 其他配置...
}
geo
模块可以创建基于IP的变量,更灵活地控制访问:
geo $allowed_ip {
default 0;
192.168.1.100 1;
10.0.0.0/8 1;
}
server {
location / {
if ($allowed_ip = 0) {
return 403;
}
# 其他配置...
}
}
map
模块也可以实现类似功能:
map $remote_addr $allowed {
default 0;
192.168.1.100 1;
10.0.0.0/8 1;
}
server {
location / {
if ($allowed = 0) {
return 403;
}
# 其他配置...
}
}
可以针对特定路径设置IP限制:
location /admin {
allow 192.168.1.100;
deny all;
# 其他配置...
}
可以同时使用IP限制和HTTP基本认证:
location /secure {
allow 192.168.1.100;
deny all;
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
192.168.1.0/24
表示整个子网nginx -t
测试配置语法http
、server
或location
上下文中deny all
不会意外阻止合法流量通过以上方法,您可以灵活地控制哪些IP地址可以访问您的Nginx服务。