微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在不改变上游的情况下控制 Nginx 反向代理的缓存?

如何解决如何在不改变上游的情况下控制 Nginx 反向代理的缓存?

我设置了一个 Nginx 反向代理,其中上游源是一个我无法修改的应用程序。我希望 Nginx 缓存静态资产(图像、脚本、样式),但始终提供新鲜的内容(html、json 等)。我有一个 proxy_cache_path 设置(似乎正在工作),我使用 $sent_http_content_type 设置了一个地图,它正确地提供了 Cache-Control 和 Expires 标头。但是,除非我proxy_ignore_headers Cache-Control;,否则 Nginx 不会缓存任何内容。但现在正在缓存所有内容 (x-cache-status: HIT):

Response Headers

我的相关配置部分看起来像这样...

proxy_cache_path /var/run/Nginx-cache levels=1:2 keys_zone=FOUNDRY:10m inactive=24h max_size=1g use_temp_path=off;

# Expires map
map $sent_http_content_type $expires {
  default off;
  "text/html" epoch;
  "text/html; charset=utf-8" epoch;
  "text/css" 1w;
  "text/css; charset=UTF-8" 1w;
  "application/javascript" 1w;
  "application/javascript; charset=UTF-8" 1w;
  ~image/ 1w;
  ~audio/ 1w;
  ~application/font 1y;
}


server {
  listen 443 ssl http2;
  server_name _;
  client_max_body_size 300M;

  more_clear_headers Server;
  more_clear_headers X-Powered-By;
  more_clear_headers ETag;

  location / {

    proxy_cache FOUNDRY;
    proxy_cache_valid 200 1d;
    proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
    proxy_ignore_headers Cache-Control;
    proxy_cache_lock on;

    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    proxy_pass http://localhost:30000;

    #cache static content
    expires $expires;
    add_header X-Cache-Status $upstream_cache_status;
  }

}

无法控制上游时,如何通过 mimetype 控制 Nginx 缓存的内容

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。