Nginx close upstream connection after request

Nginx was configured as reverse proxy for an upstream server that servers a website. Upon checking the setup I encountered the 502 Bad gateway error. In Nginx error.log I found the following line:

I spent some time playing around with a config but the right direction for digging was found once I examined the outgoing package:

The fourth line "Connection: close\r" showed that Nginx sends Connection: close header to the upstream server so the connection is terminated.

So what we need is to keep alive the connection between Nginx and upstream server.

For HTTP (like in my case) the proxy_http_version directive should be set to “1.1” and the “Connection” header field should be cleared:

Alternatively, HTTP/1.0 persistent connections can be used by passing the "Connection: Keep-Alive" header field to an upstream server, though this method is not recommended.

Adding the

directives solved my problem and 502 Bad gateway error was fixed.

Example configuration of memcached upstream with keepalive connections:

For FastCGI servers, it is required to set fastcgi_keep_conn for keepalive connections to work:

When using load balancer methods other than the default round-robin method, it is necessary to activate them before the keepalive directive.

SCGI and uwsgi protocols do not have a notion of keepalive connections.

Good luck!

Want me to do this for you? Drop me a line: itgalaxyzzz {at} gmail [point] com