反向代理配置静态文件的 客户端缓存
重点看expires
配置。
结果示例:
location / {
proxy_pass http://localhost:23333/;
root /data/wwwroot;
index index.html index.htm;
proxy_set_header Host localhost;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header REMOTE-HOST $remote_addr;
# 必须的 Websocket 支持
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
add_header X-Cache $upstream_cache_status;
add_header Cache-Control no-cache;
#expires -1;
if ($request_filename ~ .*\.(ico|css|js|png|jpg|jpeg|woff)$) # 如果文件是.css或.js 则,增加响应头
{
#add_header my-test "$request_filename" always; # 测试查看变量值
expires 30d; # 该配置替换了下面的配置
#add_header Cache-Control max-age=36003600; # 返回200 测试强制缓存,不会发起请求(不会有请求头)
#add_header Cache-Control no-cache; # 测试代码 返回304 测试协商缓存,会发起请求,确认资源是否更改(请求头会有 If-None-Match【对应etag】 If-Modified-Since【对应last-modified】 字段,确认资源是否变更)
# add_header Cache-Control no-store; # 测试代码 返回200 不缓存,必然要发起全新的请求(自然不会有 If-Modified-Since 等字段)
}
}
一般缓存配置示例
# 静态文件
location ~ ^/web/.*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)$ {
expires 20d;
access_log off;
}
location ~ ^/web/.*\.(js|css)?$ {
expires 7d;
access_log off;
}
配置协商缓存示例
解决了静态资源修改后不更新的问题
# 公共静态页面
location / {
add_header Cache-Control no-cache; # 加上这个响应头,表示协商缓存,解决了静态资源修改后不更新的问题
index index.html index.htm;
}