Remove "Connection: keep-alive" response header in NGINX 204 response with HTTP/1.1
Asked Answered
H

1

10

In any response served by NGINX, how can one remove the "Connection: keep-alive" header?

We serve 100B+/month of sub 100-byte responses to under 10 clients from NGINX for RTB based ad serving. We're attempting to minimize the overhead (data size) to save on bandwidth costs. We do not want to actually have NGINX close the connection, only remove it from the header. The client is not a browser and will leave the connection open as per the HTTP/1.1 spec.

We have successfully removed the default response headers from our "no operation" response (204) using HttpHeadersMoreModule. It looks like this:

HTTP/1.1 204 No Content
Connection: keep-alive

We want to remove the other header so it looks like this:

HTTP/1.1 204 No Content

Our keepalive_timeout is set without a second value. As per NGINX HttpCoreModule documentation, without this [second] parameter, nginx does not send a Keep-Alive header. Out setting is:

keepalive_timeout 60s;

We've tried using and setting both http://wiki.nginx.org/HttpHeadersMoreModule#more_clear_headers and http://wiki.nginx.org/HttpHeadersMoreModule#more_clear_input_headers:

more_clear_headers 'Connection';
more_clear_input_headers 'Connection';

We've also tried:

rewrite_by_lua '
    ngx.req.clear_header("Connection")
    ';

And even the:

more_clear_headers 'Connection*';

But we still see the header. We send so many responses that the Connection header actually costs us like $200 dollars a month.

Any help is appreciated.

Related and helpful: Nginx and raw headers

Hehre answered 4/1, 2014 at 9:29 Comment(2)
as pointed out by @agentzh here: github.com/agentzh/headers-more-nginx-module/issues/…, "The only way to actually remove the Connection header is to patch the Nginx core, that is, editing the C function ngx_http_header_filter in the src/http/ngx_http_header_filter_module.c file."Hehre
It's a violation of HTTP/1.1 to omit the Connection header. It is legal to do it in HTTP/1.0, though. But if that client is making more than one request before the timeout, the traffic of additional TCP handshakes will cost you a lot more bandwidth and server resources than the few bytes of that header. But if one is bent on doing this, you can also un-gracefully kill the TCP session with a reset by setting reset_timedout_connection on and keepalive_requests 1, to avoid the 4-way TCP close. This is all abuse of the protocol, though.Hypoplasia
P
2

I don't know if this works in your case, but I had the same issue and I fixed it using keepalive_requests:

    location xxx {
      keepalive_requests 1;
 
      ....

    }
Pyrone answered 27/6, 2022 at 10:52 Comment(1)
This will disable keep-alive. From the keepalive_requests doc: "After the maximum number of requests is made, the connection is closed.".Texture

© 2022 - 2024 — McMap. All rights reserved.