nginx---cors跨域风险修复和防止Host头攻击

发布时间:2026/7/24 22:42:02
nginx---cors跨域风险修复和防止Host头攻击 经过两天的折腾试了很多方法最后总结下有效的设置location /test/abc/ { #防止修改Host头攻击 if ($http_Host ! ***.***.com:15689){ return 403; } #不允许任意跨域访问 set $andflag 0; set $cors ; #后台已设置Access-Control-Allow-Origin *,先删除 proxy_hide_header Access-Control-Allow-Origin; #origin头不为空跨域请求会存在origin头 if ($http_origin) { set $andflag 1; } #从白名单跨域 if ($http_origin https://***.***.com:15689) { set $cors $http_origin; set $andflag ${andflag}1; add_header Access-Control-Allow-Origin $cors; } #有origin头并且不在白名单 if ($andflag 1) { return 505; } proxy_pass http://10.1.**.**:12345/api/test/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Cookie $http_cookie; }