Nginx:配置put和delete方法转发
由于历史原因,最原始的 http 里面 put 允许不经过验证机制匿名上传文件,造成了大规模的恶意攻击事件,因此很多 old-fashioned 扫描人员会直接报告说支持 put, delete, options 就是不安全。
因此要么强制 https,防火墙和扫描就无法知道请求的 method 具体是什么;要么在 nginx 中配置put和delete方法的转发。
对于前端而言,首先需要将所有 delete 和 put 请求先处理成 post 请求,对于 Vue 项目,只需要在 axios 中对请求的拦截配置中加入:
axios.interceptors.request.use(
config => {
const method = (config.method || '').toLowerCase();
if (method === 'put' || method === 'delete') {
config.method = 'post';
config.headers['X-HTTP-Method-Override'] = method;
}
return config;
})
这样将真正的 method 放在了请求头的 X-HTTP-Method-Override
字段,nginx 再根据请求头的 X-HTTP-Method-Override
重新修改请求回 delete 和 put,最后发送到后端。
具体的,nginx中需要加入:
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
set $method $request_method;
if ($http_x_http_method_override ~* "DELETE") {
set $method DELETE;
}
if ($http_x_http_method_override ~* "PUT") {
set $method PUT;
}
proxy_method $method;
}
修改完后,需要让 nginx 重载配置文件, 使用 nginx -s reload
命令即可。
Last modified on 2023-10-24