nginx nodejs 502 upstream prematurely closed connection while reading response header from upstream

问题描述:

在nginx + nodejs的应用场景中,请求URL中如果含有不能进行编码的非法字符则nodejs http server会直接socket hang up断开连接,导致nginx报错"upstream prematurely closed connection while reading response header from upstream", nginx对客户端返回502错误。

测试了Nodejs的两个版本v4.5.0和v8.11.4,都是这种处理方式,且不输出错误日志。作为参照java的tomcat对于这种情况的处理是:返回400错误,同时记录一条错误日志。

示例URL:

如果请求是由前端javascrip脚本发起,则时常会有非法字符出现,如读取客户端mac

http://test.pengpengzhou.com/data?mac=CF-頛摾$▒?&uid=1536675808a106e

解决方案:

在nginx.conf里增加过滤条件,对含有非法字符的请求直接返回400错误,不再转发。

if ( $request_uri ~ [^A-Za-z0-9:\.\/\?@&=\$%,#\+\-_!~\;'\[\]\{\}\^] ) {
  return 400;
}
发布了51 篇原创文章 · 获赞 3 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/pengpengzhou/article/details/82699383