NginX 上设置静态缓存的过期时间

前言:说到这个缓存就想起之前学校叫我们写实习日志的网站,不得不说那个网站设置的客户端缓存周期真的是长到飞起。每当我修改完一次实习报告之后交给老师,老师总是抱怨我怎么没改完就又交了一遍。我后来在同学的提醒下才发现原来是缓存内容没更新直接读取了。这也导致每次老师重新批阅学生实习报告都得清理一下浏览器缓存。

使用方法

写在Location域内或if语句中。
s代表秒,m代表分钟,h代表小时,d代表天数。
若想要设置具体时间,还需要在具体时间前加上@。因为可以写在不同的作用域内,因此可以对某些静态文件不设置缓存,设置为Off即可。
location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
    expires 1h30m15s;
    // expires @1h30m15s;
    // expires max;
    // expires off;
    add_header Cache-Control "public";
}

除时间之外Expires可传入的参数

Parameter Explain
off Turns off Nginx cache headers logic.
epoch purge a stored resource from all caches by setting the Expires header to “1 January, 1970 00:00:01 GMT”.
max This is the opposite of the “epoch” value. the Cache-Control max-age set to 10 years.

温馨提示

设置缓存时请正确设置服务器时间,附上Linux设置时间的方法。
比如这种简单粗暴的:
date -s '2017-08-26 23:00:00'

clock -w // writting time into CMOS
当然有的时候是时区设置错误,这里给一个设置时区的方法:
date -R // show current time zone

ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

参考资料

评论