我有一个在 nginx 后面运行的 ExpressJS 应用程序,我将其设置为反向代理。我还为图像、js 和 css 等静态文件设置了一些缓存。问题是,它们似乎并没有真正进行缓存。对这些文件的请求始终返回 200 状态代码而不是 304。如果我检查开发工具中的 header ,Expires header 永远不会与我上次请求该文件时相同。它总是会重置为新值。我的配置中是否遗漏了某些内容?
我使用的是 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;
}
}
最佳答案
您在 header 中看到的到期时间随每个请求而变化是正常的,因为,如 doc says :
A time in the “Expires” field is computed as a sum of the current time and time specified in the directive.
(强调。)当前时间是请求的时间。由于当前时间随每个请求而变化,因此到期时间也会变化。如果您想要使用文件的上次修改时间,则可以使用 expires modded 7d
。
现在,通过将到期日期设置为 future 7 天,您就是在告诉浏览器在到期之前不必再次检查。 7 天后,当浏览器再次检查时,您将收到 304。如果您希望浏览器在尝试再次加载资源时始终进行检查,请设置expires 0
。
关于node.js - 使用 nginx 作为反向代理时,缓存静态文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22580098/