1. 程式人生 > >nginx nodejs 502 upstream prematurely closed connection while reading response header from upstream

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:\.\/\[email protected]&=\$%,#\+\-_!~\;'\[\]\{\}\^] ) {
  return 400;
}