在Nginx反向代理配置中,实现多版块访问控制是常见的需求,特别是当您需要为不同URL路径或子域名设置不同的访问规则时。以下是几种有效的多版块访问控制策略实现方法。
server {
listen 80;
server_name example.com;
# 公共区域 - 允许所有人访问
location /public/ {
proxy_pass http://backend_server/public/;
}
# 内部区域 - 仅允许特定IP
location /internal/ {
allow 192.168.1.0/24;
deny all;
proxy_pass http://backend_server/internal/;
}
# 管理区域 - 需要HTTP基本认证
location /admin/ {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://backend_server/admin/;
}
}
# 主站点 - 公开访问
server {
listen 80;
server_name example.com;
proxy_pass http://backend_server;
}
# 内部站点 - IP限制
server {
listen 80;
server_name internal.example.com;
allow 192.168.1.0/24;
deny all;
proxy_pass http://internal_backend;
}
# API站点 - 需要Token认证
server {
listen 80;
server_name api.example.com;
location / {
if ($http_authorization != "Bearer your-secret-token") {
return 403;
}
proxy_pass http://api_backend;
}
}
map $uri $allow_access {
default 0;
~^/public/ 1;
~^/internal/ 0;
~^/api/v1/ 1;
~^/api/v2/ 0;
}
server {
listen 80;
server_name example.com;
location / {
if ($allow_access = 0) {
return 403 "Access Denied";
}
proxy_pass http://backend_server;
}
}
geo $allowed_country {
default no;
192.168.1.0/24 yes; # 内部网络
US yes; # 允许美国
GB yes; # 允许英国
# 其他允许的国家...
}
server {
listen 80;
server_name example.com;
location / {
if ($allowed_country = no) {
return 403 "Access from your region is not allowed";
}
proxy_pass http://backend_server;
}
}
map $date_local $allow_access {
default 0;
"~*Mon-Fri, 08:00-18:00" 1;
}
server {
listen 80;
server_name example.com;
location /work-hours/ {
if ($allow_access = 0) {
return 403 "Access only allowed during work hours (Mon-Fri, 8AM-6PM)";
}
proxy_pass http://backend_server/work-hours/;
}
}
通过合理组合这些策略,您可以构建一个灵活而强大的多版块访问控制系统,满足不同业务场景的安全需求。