expire指令
Syntax: expires [modified] time;
expires epoch | max | off;
Default: expires off;
Context: http, server, location, if in location
expire指令用来告诉浏览器缓存过期时间的,设置缓存,可以提高网站性能。当网站的部分内容,比如新闻站的图片,一旦发布就不太可能发生更改,此时需要用户在访问一次页面之后,把该页面的图片缓存在用户的浏览器端一段时间,就可以用到 nginx 的 expires 设置。要配置expires,可以在http段中或者server段中或者location段中加入。
expire 设置完之后的,访问一次网页后,对应的静态文件就存到了浏览器中,后面再次请求状态码就是304,也就是从缓存中获取文件设置完后重启nginx生效, 建议平滑重启nginx (不会影响网站)
location / {
expires 1h; #一个小时后过期
root html;
index index.html index.htm;
}
[root@localhost ~]# date -u
Tue May 26 01:54:10 UTC 2020
[root@localhost ~]# curl 192.168.179.99 -I
HTTP/1.1 200 OK
Server: nginx/1.16.0
Date: Tue, 26 May 2020 01:52:15 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Mon, 25 May 2020 07:36:21 GMT
Connection: keep-alive
ETag: "5ecb7575-264"
Expires: Tue, 26 May 2020 02:52:15 GMT #Date时间和Expires时间间隔刚好是一个小时
Cache-Control: max-age=3600 #设置一小时过期可以看到max-age即为3600,正好是一个小时
Accept-Ranges: bytes
location / {
expires 1h; #一个小前过期
root html;
index index.html index.htm;
}
[root@localhost ~]# date -u
Tue May 26 01:57:31 UTC 2020
[root@localhost ~]# curl 192.168.179.99 -I
HTTP/1.1 200 OK
Server: nginx/1.16.0
Date: Tue, 26 May 2020 01:57:35 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Mon, 25 May 2020 07:36:21 GMT
Connection: keep-alive
ETag: "5ecb7575-264"
Expires: Tue, 26 May 2020 00:57:35 GMT
Cache-Control: no-cache #即资源被缓存,但是缓存立刻过期, 同时下次访问时强制验证资源有效性
Accept-Ranges: bytes
测试:未配置expire访问图片
访问 http://192.168.254.100/
图片 nginx.png 的响应状态是 200 ok,此时图片的 http 头信息:
再次刷新该页面
图片 nginx.png 的响应状态是 304 Not Modified,即来自浏览器缓存,此时图片的的 http 头信息:
虽然图片该次是从浏览器缓存中读取,但是浏览器仍然向服务器发出了一次 http 请求
配置expire
如果要实现在一定时间内,浏览器不需要向服务器发送 http 请求,而直接从本地缓存中读取图片,可以在 nginx.conf 中进行配置:
location ~*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)$ {
root /usr/local/nginx/html/images/;
expires 30d; # 30m:30 分钟,2h:2 小时,30d:30 天
access_log off;
}
expires 的上下文包括 location、if in location
平滑重启 nginx,平滑重启 nginx,刷新该页面,此时图片的 http 响应信息:
86400 是 1 天的秒数。再次刷新该页面(按浏览器的刷新按钮):
没有产生实际请求。在 chrome 浏览器下,通过地址栏回车刷新页面时的 http 响应信息:
from cache 表名没有产生实际请求。