Nginx可以通过检查HTTP请求头来实现精细化的访问控制。以下是几种常见的基于请求头的访问控制配置方法:
location / {
# 允许带有特定User-Agent的请求
if ($http_user_agent ~* (curl|wget)) {
return 403;
}
# 只允许带有特定自定义头的请求
if ($http_x_custom_header != "expected_value") {
return 403;
}
}
map $http_x_api_key $is_valid_key {
default 0;
"12345-67890" 1;
"abcdef-ghijk" 1;
}
server {
location /api/ {
if ($is_valid_key = 0) {
return 403 "Invalid API Key";
}
# 正常处理请求
}
}
location /secure/ {
# 必须同时满足两个条件
if ($http_x_auth_token = "") {
return 401;
}
if ($http_x_requested_with != "XMLHttpRequest") {
return 403;
}
# 正常处理请求
}
location /private/ {
auth_request /auth;
# 其他配置...
}
location = /auth {
internal;
proxy_pass http://auth-server;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
proxy_set_header X-Original-Method $request_method;
# 传递需要的请求头
proxy_set_header Authorization $http_authorization;
}
location /admin/ {
add_header X-Admin-Access "true" always;
# 检查自定义头
if ($http_x_admin_token != "secret123") {
return 403;
}
}
location /downloads/ {
valid_referers none blocked server_names *.example.com;
if ($invalid_referer) {
return 403;
}
}
通过合理配置请求头检查,可以实现API密钥验证、CSRF防护、爬虫控制等多种安全策略。