nginx proxy_pass代理转发 node 服务路径含utf8 encoded 导致404

1,409 阅读1分钟

这是我参与8月更文挑战的第1天,活动详情查看:8月更文挑战

背景:

  1. 服务器 8080 端口启动 node 服务,提供一些 api 请求 (GET/POST/PATCH/PUT/DELETE)
  2. 服务器 80 端口由 nginx 代理,访问 /json 时,使用 proxy_pass 反向代理到 8080端口的node服务

出现情况

当向 xxx.xx.com/json 发送 GET/POST/PATCH 请求时接口均正常运行,但是在发送 DELETE /services/:servicename 请求时报错,对此请求进行研究,出现以下案例:

  1. DELETE xxx.xx.com/json/services/redux ok
  2. DELETE xxx.xx.com/json/services/@orgName/microA 404 fail
  3. DELETE xxx.xx.com/json/services/%40orgName%2FmicroA 404 fail
  4. DELETE xxx.xx.com:8080/services/redux ok
  5. DELETE xxx.xx.com:8080/services/%40orgName%2FmicroA ok

结论

RESTFUL 风格的路径参数请求,如果参数中包含转义字符,在使用 nginx proxy_pass 反向代理时,会导致请求失败

Nginx 部分配置如下

location /json/ {
    add_header Access-Control-Allow-Origin *;
    proxy_set_header Host $proxy_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass  http://xxx.xx.com:8080/;
    root /usr/share/nginx;
}

思考🤔

当路径存在转义字符时,使用nginx代理的请求会导致 404,而 404 则是未匹配到请求路径,但是直接访问node服务时请求是成功的,所以得出在带转义字符的请求发送到nginx时nginx对已经转义过的url进行了处理,导致不能正确匹配。

修改 Nginx proxy_pass 配置

proxy_pass  http://xxx.xx.com:8080/;
if ($request_uri ~* ^/json/(.*)$) {
   proxy_pass  http://xxx.xx.com:8080/$1;
}

最后

实现当访问此种带转义字符请求时,不处理url的后续参数直接转发,成功实现了 nginx proxy_pass 反向代理到 node 服务。

欢迎━(`∀´)ノ亻! 阅读