在Nginx反向代理配置中,基于请求头(HTTP Headers)的访问控制是一种常见的安全策略,可以用于限制或允许特定请求访问后端服务。以下是详细的配置方法和示例:
if
和$http_
变量进行头检查location / {
# 检查特定的请求头
if ($http_user_agent ~* (bot|spider|crawler)) {
return 403;
}
# 检查自定义头是否存在
if ($http_x_custom_header = "") {
return 403;
}
proxy_pass http://backend;
}
map
指令进行更复杂的头匹配map $http_x_api_key $is_valid {
default 0;
"12345-67890" 1;
"abcde-fghij" 1;
}
server {
location / {
if ($is_valid = 0) {
return 403;
}
proxy_pass http://backend;
}
}
location /api/ {
if ($http_x_api_key != "your-secret-key") {
return 403;
}
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://api_backend;
}
location / {
# 阻止已知的恶意User-Agent
if ($http_user_agent ~* (wget|curl|libwww-perl|nikto|sqlmap)) {
return 403;
}
# 只允许特定浏览器的访问
if ($http_user_agent !~* (chrome|firefox|safari)) {
return 403;
}
proxy_pass http://backend;
}
location /images/ {
valid_referers none blocked yourdomain.com *.yourdomain.com;
if ($invalid_referer) {
return 403;
}
proxy_pass http://image_backend;
}
location /secure/ {
if ($http_authorization = "") {
return 401;
}
# 可以进一步解析JWT令牌内容
# 需要安装ngx_http_lua_module模块
proxy_set_header Authorization $http_authorization;
proxy_pass http://secure_backend;
}
location /admin/ {
# 需要同时满足特定User-Agent和自定义头
if ($http_user_agent !~* "AdminBrowser") {
return 403;
}
if ($http_x_admin_token != "secure-token-123") {
return 403;
}
proxy_pass http://admin_backend;
}
map
和正则表达式map $http_x_device_id $is_allowed_device {
default 0;
"~^DEV-[A-Z0-9]{8}$" 1;
}
server {
location /mobile/ {
if ($is_allowed_device = 0) {
return 403;
}
proxy_pass http://mobile_backend;
}
}
map $http_x_api_version $backend {
default "http://v1_backend";
"v2" "http://v2_backend";
"v3" "http://v3_backend";
}
server {
location /api/ {
proxy_pass $backend;
}
}
nginx
http {
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;
}
nginx
log_format security '$remote_addr - $http_user_agent - $http_referer';
access_log /var/log/nginx/security.log security;
map
指令中,减少重复的正则匹配if
条件,考虑使用Nginx Plus的JWT模块等专业解决方案通过合理配置基于请求头的访问控制,可以有效地增强Nginx反向代理的安全性和灵活性。