如何在不改变上游的情况下控制 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 (将#修改为@)