Nginx gzip 压缩对 POST 的响应无效

nginx 开启 gzip 压缩可以有效地减少文本传输体积,节省流量,所以一般情况下我都是开启 gzip 的。但是,今天(现在已经半夜了,算昨天)遇到了一个非常坑的问题:POST 响应无法压缩。

一开始,对于无法压缩响应的问题,我查了很多资料,gzip 的配置看了一遍又一遍。

比如设置 gzip_http_version 为 1.0(默认是 1.1),因为我用了 proxy_pass,部分文章说用了代理是 http 1.0 协议,所以要设为 1.0。

再比如将 gzip_vary 设为 off,因为设为 on 的时候,nginx 会根据请求头的 Accept-Encoding 决定是否压缩。但我看请求头里是有 Accept-Encoding 的。

再比如,有一篇文章说什么防火墙将 nginx 压缩后的内容解压了,并去掉了 content-encoding: gzip。但我同一台服务器上的其他静态资源就可以压缩。

……

总之,各种配置都试了,就是无法压缩 POST 接口的响应。最后,我在 github 看到了这个 issue:help request: The gzip plugin doesn’t work for POST requests with a response code of 201。这个 issue 最后一个回答如下:

https://mailman.nginx.org/pipermail/nginx/2012-September/035338.html
I looked at the gzip package of nginx used by the bottom layer. I found this discussion. It should be that the bottom layer does not support the compression of the 201 response code!

就是说 nginx 所使用的底层库本身不支持部分状态码响应的压缩。比如 206 不包含完整的响应实体,而 304 则没有响应实体……

总之,这个问题很坑,nginx 的模块文档里也没有说明这点。

资源列表我还是改用 GET 请求吧。


但是,也不是说 post 请求响应体就肯定无法压缩,这个其实和响应码有关,post 返回 200 就可以了。