我已经configurationNginxcaching来自上游服务器的所有响应,总是返回Cache-Control: public, max-age=1但nginx似乎caching了响应2秒。 怎么来的?
更具体地说,我的上游服务器是一个简单的Express.js(节点)应用程序返回当前时间:
app.get('/', function (req, res) { res.setHeader('Cache-Control', 'public, max-age=1'); res.send((new Date()).toISOString()); });
这是相关的nginxconfiguration:
http { proxy_cache_path /data levels=1:2 keys_zone=zuul:10m max_size=10g; ... server { location / { proxy_cache zuul; proxy_pass http://zuul; proxy_cache_use_stale updating; proxy_cache_background_update on; } listen 0.0.0.0:80 default_server; } }
然后我在一个循环中curl http://localhost ,希望看到响应(包含node.js看到它的时间戳)每秒都在变化。 而不是每两秒钟更改一次。 就好像Nginx不愿caching响应的时间less于两秒钟,并不尊重上游返回的max-age 。
我如何说服Nginxcaching响应
这可能是proxy_cache_use_stale更新,结合proxy_cache_background_update 。 文件说
proxy_cache_use_stale
确定在与代理服务器进行通信期间,可以在哪些情况下使用陈旧的caching响应。
如果更新参数当前正在更新,则允许使用陈旧的caching响应。 这允许在更新caching数据时最小化对代理服务器的访问次数。
proxy_cache_background_update
允许启动后台子请求来更新过期的caching项,而过时的caching响应则返回给客户端。 请注意,有必要在更新时允许使用陈旧的caching响应。
在我看来,它正在做你已经告诉它做的事情。
可能的scheme
我怀疑你想要的是
proxy_cache_use_stale off; proxy_cache_background_update off;
放弃
这可能不是OPs问题的解决scheme。 我在find标题中的确切问题的答案时发现了这个话题(这在谷歌search结果中很高)。 我发布这个答案,因为有人可能会发现它像我这样的话题后有用。
回答
在我的情况下,我发现指令设置为
proxy_cache_valid 200 302 30m; proxy_ignore_headers Set-Cookie X-Accel-Expires Expires Cache-Control;
而nginx并没有考虑到Cache-Control头部中的max-age ,并且所有内容都被caching了半个小时。 这些指令被隐藏在nginx.conf文件中而不是vhostconfiguration中,所以确保你也检查那个地方。 我从第二个指令中删除了Cache-Control ,现在每一个都正确caching。