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

POST response caching does not work in nginx

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

nginx.confhttp部分中,我具有以下内容:

1
proxy_cache_path /tmp/cache keys_zone=cache:10m levels=1:2 inactive=600s max_size=100m;

然后我在server中有location

1
2
3
4
5
6
7
8
9
10
11
12
13
    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;
    }

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

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

1
curl -v --data"a=b&c=d" https://my-host/my-url/1573

它们都到达后端(根据后端日志)。 同样,X-Cached始终为MISS

请求和响应如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
> 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

因此,缓存不起作用。

  • 我在这里做错了什么?
  • nginx中是否有任何日志记录工具可以查看为什么它选择不缓存响应?

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

    1
    proxy_buffering off;

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

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

  • 服务器上的输出Cache-Control: public, max-age=10标头
  • 在Nginx中添加proxy_cache_path配置和location配置(问题文本中提供了示例)
  • 对于要启用缓存的位置,请确保proxy_bufferingon