闽公网安备 35020302035485号
缓存是什么,为什么要学习 Nginx 如何配置缓存?我们知道,在性能优化中,缓存是其中非常重要的一环。学会缓存,可以提高用户的体验,减轻服务器的压力,如果对其不了解,也许在平时的开发中,遇到缓存问题,你也许会很苦恼。本文主要介绍 Nginx 客户端如何命中本地的缓存。
| 值 | 描述 |
|---|---|
| no-store | 禁止缓存(强缓存和协商缓存),客户端不存储任何值 |
| no-cache | 禁止强缓存,需要重写验证(可以理解为 禁止强缓存,启用协商缓存) |
| private | 私有缓存,禁止中间人(比如CDN等代理缓存) |
| public | 共享缓存,允许中间人缓存 |
| max-age | 资源可以被缓存的最大时间,单位:秒,是一个相对时间,优先级高于 Expires |
| s-maxage | 用于共享缓存,单位:秒,如果在其有效期内,不去访问CDN等。s-maxage会覆盖 max-age 和 Expires |
| must-revalidate | 缓存使用陈旧资源时,必需先验证状态 |
location /test {
add_header Cache-Control "private, max-age=25920000";#开启私有缓存 缓存1个月
}
location /test {
add_header Expires "10d";#缓存10天
}
协商缓存location /test {
etag off;
}
关闭 Last_Modifiedlocation /test {
add_header Last-Modified '';
if_modified_since off;
}
正常情况下,不建议关闭协商缓存
add_header Pargma 'no-cache'; #禁止缓存
.css、js、图片等资源,使用强缓存。配合webpack的文件指纹策略,打包的时候文件名带上hash值,这样有改动,hash值就会发生变化,达到让客户端缓存失效的目的


server {
listen 80;
server_name 127.0.0.1;
root /opt/nginx/frontEnd;
# 压缩配置
gzip on;
gzip_comp_level 6;
gzip_min_length 1k;
gzip_types image/png image/jpeg image/gif image/svg+xml application/javascript;
gzip_vary on;
# 缓存相关字段的设置
location /test {
index index.html index.htm;
# js、css、字体、图片等资源启用强缓存
if ($request_uri ~* .*[.](js|css|map|jpg|png|svg|ico)$) {
add_header Cache-Control "public, max-age=25920000";#非html缓存1个月
add_header Expires "30d";
}
# HTML 启用协商缓存
if ($request_filename ~* ^.*[.](html|htm)$) {
add_header Cache-Control "public, no-cache";
}
}
}
| 请求头字段 | 描述 | 响应头字段 |
|---|---|---|
| Accept | 告知服务器发送何种类型的媒体数据 | Content-Type |
| Accept-Language | 告知服务器发送何种语言 | Content-Language |
| Accept-Charset | 告知服务器发送何种字符集 | Content-Type |
| Accept-Encoding | 告知服务器采用何种压缩方式 | Content-Encoding |