nginx反向代理禁用缓存

Kév*_*lin 6 nginx no-cache nginx-reverse-proxy

我使用 nginx 作为反向代理来连接 api。问题是当我在添加或删除某些内容后发送查询时。Nginx 将旧的 json 值发送给我。我试图禁用缓存,但它不起作用。

我的 nginx 配置:

location  / {

  sendfile off;
  add_header Last-Modified $date_gmt;
  add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
  if_modified_since off;
  expires off;
  etag off;
  proxy_no_cache 1;
  proxy_cache_bypass 1;

  proxy_pass http://127.0.0.1:5000;
  proxy_set_header Host $http_host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-Proto $scheme;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header HTTPS   $https;
}
Run Code Online (Sandbox Code Playgroud)

我尝试在没有 nginx 的情况下进行查询,并且在控制台中一切正常

谢谢你!

bdz*_*aid 11

根据文档proxy_cache你必须更换

proxy_no_cache 1;
proxy_cache_bypass 1;
Run Code Online (Sandbox Code Playgroud)

proxy_no_cacheproxy_cache_bypass定义了不将响应保存到缓存的条件。

然后要禁用缓存,您可以将这两个条件替换为

proxy_cache 关闭;

这是一个完整的示例,您可以使用它为无状态 api 服务器配置代理

location /myapi {

        # Proxy 
        proxy_set_header                X-Localhost true;
        proxy_set_header                X-Real-IP $remote_addr;
        proxy_set_header                X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass                      http://localhost:8080/myapi;

        proxy_redirect                  off;
        proxy_buffers                   32 16k;
        proxy_busy_buffers_size         64k;
        proxy_cache                     off;


        # Headers for client browser NOCACHE + CORS origin filter 
        add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        expires off;
        add_header    'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
        add_header    'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept' always;

        allow all;
    }
Run Code Online (Sandbox Code Playgroud)

  • 升级到 ES 7.7 后,我缺少“proxy_cache off”。你让我很高兴,非常感谢你! (2认同)