【问题标题】:POST response caching does not work in nginxPOST 响应缓存在 nginx 中不起作用
【发布时间】:2018-10-18 02:02:06
【问题描述】:

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

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

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

然后我在server 中有location

    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 发出重复请求时

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

所有这些都到达后端(根据后端日志)。此外,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

所以缓存不起作用。

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

【问题讨论】:

  • 缓存一定要用nginx吗?你可以试试nustergithub.com/jiangwenyuan/nuster,轻松实现你的要求
  • @nustercacheserver 谢谢,我会考虑 nuster

标签: nginx caching http-post nginx-location nginx-cache


【解决方案1】:

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

proxy_buffering off;

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

因此,要使缓存适用于 POST 请求,我们必须执行以下操作:

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

【讨论】:

  • 这个答案和问题一起,不仅解决了原来的问题,而且作为设置nginx POST缓存的简明教程。你使我免于大量的反复试验。问得好,回答得好。
猜你喜欢
  • 2016-02-18
  • 2017-11-30
  • 2015-07-05
  • 2021-10-21
  • 1970-01-01
  • 1970-01-01
  • 2012-09-12
  • 2016-12-06
  • 2018-05-07
相关资源
最近更新 更多