nginx修复cors漏洞
背景:
渗透测试发现cors漏洞
处理:
server {
listen 80;
server_name your.domain.com;
location / {
# 检查Origin是否在允许列表中
if ($http_origin ~* (https://example\.com|https://sub\.example\.com|http://localhost(:[0-9]+)?)) {
add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
}
# 如果Origin存在但不在允许列表中,返回403
if ($http_origin) {
set $cors_check "pass";
}
if ($http_origin !~* (https://example\.com|https://sub\.example\.com|http://localhost(:[0-9]+)?)) {
set $cors_check "${cors_check}fail";
}
if ($cors_check = "passfail") {
return 403;
}
# 处理OPTIONS预检请求
if ($request_method = 'OPTIONS') {
return 204;
}
# 你的其他代理或处理配置
proxy_pass http://backend;
}
}

浙公网安备 33010602011771号