Nginx可以通过多种方式实现访问控制,包括目录白名单和IP白名单。以下是详细的配置方法:
server {
listen 80;
server_name example.com;
# 允许所有人访问根目录
location / {
root /var/www/html;
index index.html;
}
# 限制/admin目录只允许特定IP访问
location /admin/ {
allow 192.168.1.100;
allow 10.0.0.0/24;
deny all;
root /var/www/html;
index index.html;
}
}
location /secure/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
root /var/www/html;
}
http {
# 允许的IP列表
allow 192.168.1.100;
allow 10.0.0.0/24;
deny all;
server {
listen 80;
server_name example.com;
...
}
}
server {
listen 80;
server_name example.com;
# IP白名单
allow 192.168.1.100;
allow 10.0.0.0/24;
deny all;
...
}
http {
# 定义IP组
geo $whitelist {
default 0;
192.168.1.100 1;
10.0.0.0/24 1;
}
server {
listen 80;
server_name example.com;
# 如果不是白名单IP则返回403
if ($whitelist = 0) {
return 403;
}
...
}
}
server {
listen 80;
server_name example.com;
# 默认允许所有IP访问公共区域
location / {
root /var/www/html/public;
index index.html;
}
# 管理后台 - 需要特定IP
location /admin/ {
allow 192.168.1.100;
allow 10.0.0.0/24;
deny all;
root /var/www/html/admin;
index index.html;
}
# API接口 - 需要认证
location /api/ {
auth_basic "API Access";
auth_basic_user_file /etc/nginx/.htpasswd;
root /var/www/html/api;
index index.php;
}
}
nginx -s reload
map
或geo
模块# 在nginx.conf中
http {
include /etc/nginx/whitelist.conf;
}
# /etc/nginx/whitelist.conf内容
allow 192.168.1.100;
allow 192.168.1.101;
# ...更多IP
对于更严格的安全要求,可以在操作系统防火墙层面(如iptables/nftables)设置IP白名单,作为Nginx配置的补充。
希望这些配置示例能帮助您实现Nginx的访问控制需求。根据您的具体场景选择适合的方案。