Nginx作为静态资源web服务的浏览器缓存原理与场景
浏览器缓存遵循HTTP协议定义的缓存机制(如:Expires;Cache-control等)。
当浏览器请求响应流程
浏览器缓存效验机制
校验是否过期 | Cache-Control(max-age) Expires |
协议中Etag头信息校验 | Etag |
Last-Modified头信息校验 | Last-Modified |
2. Nginx控制浏览器缓存配置
Nginx通过添加Cache-Control(max-age)、Expires头信息的方式控制浏览器缓存。
ngx_http_headers_module
语法
Syntax: expires [modified] time;
expires epoch | max | off;
Default: expires off;
Context: http, server, location, if in location
“Expires”头信息中的过期时间为当前系统时间与您设定的 time 值时间的和。如果指定了 modified 参数,则过期时间为文件的最后修改时间与您设定的 time 值时间的和。“Cache-Control”头信息的内容取决于指定 time 的符号。可以在time值中使用正数或负数。
当 time 为负数,“Cache-Control: no-cache”;
当 time 为正数或0,“Cache-Control: max-age=time”,单位是秒。
epoch 参数用于指定“Expires”的值为 1 January, 1970, 00:00:01 GMT。
max 参数用于指定“Expires”的值为 “Thu, 31 Dec 2037 23:55:55 GMT”,“Cache-Control” 的值为10 年。
off 参数令对“Expires” 和 “Cache-Control”响应头信息的添加或修改失效。
3. 应用实例 (编辑nginx的配置文件)
1. vim /etc/nginx/conf.d/static.conf
server {
location ~ .*\.(txt|xml)$ {
# 设置过期时间为1天
expires 1d;
root /vagrant/doc;
}
}
2. nginx -s reload 重新载入nginx配置文件3. 创建 /vagrant/doc/hello.txt 文件
4. 通过curl访问 192.168.33.88/hello.txt,查看http响应头信息
[root/etc/nginx]# curl -I 192.168.33.88/hello.txt
HTTP/1.1 200 OK
Server: nginx/1.14.0
Date: Tue, 17 Jul 2018 07:12:11 GMT
Content-Type: text/plain
Content-Length: 12
Last-Modified: Tue, 17 Jul 2018 07:07:22 GMT
Connection: keep-alive
ETag: "5b4d95aa-c"
Expires: Wed, 18 Jul 2018 07:12:11 GMT
Cache-Control: max-age=86400
Accept-Ranges: bytes
重点查看 Expires 和 Cache-Control两个字段,可见,hello.txt 的缓存时间为1天。以上是本文的全部内容,希望对大家学习有帮助,也希望大家多多支持 磊丰的技术博客 感谢阅读!