在使用 nginx反向代理功能時,因爲我們只對客戶端請求中的請求行感興趣,對請求頭和包體數據不感興趣,所以忽略了請求頭和請求包體數據(proxy_pass_request_headers proxy_pass_request_body全部off)。但是在客戶端請求是 POST並且攜帶 content內容時,nginx反向代理髮給後端請求數據中就會攜帶 Content-Length字段,可能會導致異常發生。
之前理解是 proxy_pass_request_headers設置 off後,客戶端所有請求頭全部不發送給後端服務器,但是 Content-Length好像是在 原始請求和子請求中共享,所以帶給了子請求,具體還需要看 nginx源碼。
例子:
使用nginx版本1.14.2,在使用反向代理時,如果配置文件如下:
http {
upstream upstream_test_backend {
server 192.168.240.141:6311;
keepalive 10240;
}
server {
listen 8686;
location /upstream_test {
proxy_pass http://upstream_test_backend;
proxy_http_version 1.1;
proxy_pass_request_headers off;
proxy_pass_request_body off;
proxy_set_header Connection "";
}
}
客戶端請求命令:
curl -d"1" -XPOST 127.0.0.1:8686/upstream_test
在客戶端請求是 POST並且帶有 content內容時,nginx轉發給後端的請求頭中會攜帶 Content-Length頭,但是因爲 proxy_pass_request_body off所以不攜帶包體數據。這會導致有些 HTTP服務器一直等待 content內容(Content-Length不爲0),因此和後端通信超時,請求不能正常處理。請求 HTTP數據如下:
把 nginx location裏的配置手動設置 Content-Length爲空,請求後端服務器就不會有 Content-Length頭部了,配置請求如下
http {
# ...
server {
listen 8686;
location /upstream_test {
proxy_pass http://upstream_test_backend;
proxy_http_version 1.1;
proxy_pass_request_headers off;
proxy_pass_request_body off;
proxy_set_header Connection "";
proxy_set_header Content-Length "";
}
}
HTTP請求如下: