繁体   English   中英

使用Nginx作为反向代理时无法缓存静态文件

[英]Caching static files isn't working when using nginx as a reverse proxy

我在nginx后面运行了ExpressJS应用程序,并将其设置为反向代理。 我还为图像,js和css等静态文件设置了一些缓存。 问题是,它们似乎并没有真正在缓存。 对这些文件的请求始终返回200状态代码,而不是304。如果我检查开发工具中的标头,则Expires标头永远不会与上次请求文件时的标头相同。 它始终会重置为新值。 我的配置中缺少什么吗?

我正在使用nginx 1.4.4。

谢谢。

upstream stats {
  ip_hash;
  server localhost:3000;
}

server {
  server_name app.example.com;

  access_log /var/log/nginx/stats.access.log;
  error_log /var/log/nginx/stats.error.log debug;

  root /srv/www/stats/public;

  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarder-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://stats;
    proxy_redirect off;
  }

  location ~* .(ico|css|js|gif|jpg|png)$ {
    expires 7d;
    log_not_found off;
  }
}

您在标头中看到的到期时间随每个请求而变化是正常的,因为,正如doc所说

“ Expires”字段中的时间计算为当前时间与指令中指定的时间之和。

(添加了强调。)当前时间是请求的时间。 由于当前时间随每个请求而变化,因此到期时间也随之变化。 如果您要使用的是文件的最后修改时间,那么您将使用expires modified 7d

现在,通过将到期日期设置为未来的7天,可以告诉浏览器不要再在到期前再次检查。 当浏览器在7天内再次检查时,您将获得304。 如果希望浏览器始终检查何时尝试再次加载资源,则set expires 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM