POST 响应缓存在 nginx 中不起作用

Rom*_*kiy 5 caching nginx http-post nginx-location nginx-cache

我的任务是使用nginx实现微缓存策略,即缓存一些POST端点的响应几秒钟。

http部分nginx.conf我有以下内容:

proxy_cache_path /tmp/cache keys_zone=cache:10m levels=1:2 inactive=600s max_size=100m;
Run Code Online (Sandbox Code Playgroud)

然后我locationserver

    location /my-url/ {
      root dir;
      client_max_body_size 50k;
      proxy_cache cache;
      proxy_cache_valid 10s;
      proxy_cache_methods POST;
      proxy_cache_key "$request_uri|$request_body";
      proxy_ignore_headers Vary;

      add_header X-Cached $upstream_cache_status;

      proxy_pass http://my-upstream;
    }
Run Code Online (Sandbox Code Playgroud)

该应用程序位于输出处,如果我理解正确的my-upstreamCache-Control: max-age=10,应该使响应可缓存。

但是当我在短时间内(不到10秒)使用curl发出重复请求时

curl -v --data "a=b&c=d" https://my-host/my-url/1573
Run Code Online (Sandbox Code Playgroud)

它们全部到达后端(根据后端日志)。还有,X-Cached总是MISS

请求和响应如下:

> POST /my-url/1573 HTTP/1.1
> Host: my-host
> User-Agent: curl/7.47.0
> Accept: */*
> Content-Length: 113
> Content-Type: application/x-www-form-urlencoded
> 
* upload completely sent off: 113 out of 113 bytes
< HTTP/1.1 200 OK
< Server: nginx
< Date: Tue, 08 May 2018 07:16:10 GMT
< Content-Type: text/html;charset=utf-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< Keep-Alive: timeout=60
< Vary: Accept-Encoding
< X-XSS-Protection: 1
< X-Content-Type-Options: nosniff
< Strict-Transport-Security: max-age=31536000
< Cache-Control: max-age=10
< Content-Language: en-US
< X-Cached: MISS
Run Code Online (Sandbox Code Playgroud)

所以缓存不起作用。

  1. 我在这里做错了什么?
  2. nginx 中是否有任何日志记录工具可以让您了解为什么它选择不缓存响应?

Rom*_*kiy 6

事实证明,以下指令(全局定义的)阻止了缓存工作:

proxy_buffering off;
Run Code Online (Sandbox Code Playgroud)

当我在location配置下覆盖它时proxy_buffering on;,缓存开始工作。

因此,为了使缓存能够处理 POST 请求,我们必须执行以下操作:

  1. Cache-Control: public, max-age=10服务器上的输出标头
  2. 在nginx中添加proxy_cache_pathconfig和locationconfig(问题文本中给出了示例)
  3. 确保这proxy_bufferingon我们想要启用缓存的位置。