侧边栏壁纸
博主头像
落叶人生博主等级

走进秋风,寻找秋天的落叶

  • 累计撰写 130562 篇文章
  • 累计创建 28 个标签
  • 累计收到 9 条评论
标签搜索

目 录CONTENT

文章目录

优化建议解决方案:未设置max-age或expires

2024-05-09 星期四 / 0 评论 / 0 点赞 / 99 阅读 / 4378 字

网页的缓存是由 HTTP 消息头中的 “Cache-control” 来控制的,常见的取值有 private、no-cache、max-age、must-revalidate 等,默认为private

网页的缓存是由 HTTP 消息头中的 “Cache-control” 来控制的,常见的取值有 private、no-cache、max-age、must-revalidate 等,默认为private。其作用根据不同的重新浏览方式分为以下几种情况:

(1) 打开新窗口

如果指定cache-control的值为private、no-cache、must-revalidate,那么打开新窗口访问时都会重新访问服务器。而如果指定了max-age值,那么在此值内的时间里就不会重新访问服务器,例如:

Cache-control: max-age=5表示当访问此网页后的5秒内再次访问不会去服务器。

(2) 在地址栏回车

如果值为private或must-revalidate(和网上说的不一样),则只有第一次访问时会访问服务器,以后就不再访问。如果值为no-cache,那么每次都会访问。如果值为max-age,则在过期之前不会重复访问。

(3) 按后退按扭

如果值为private、must-revalidate、max-age,则不会重访问,而如果为no-cache,则每次都重复访问

(4) 按刷新按扭

无论为何值,都会重复访问

当指定Cache-control值为“no-cache”时,访问此页面不会在Internet临时文章夹留下页面备份。

另外,通过指定“Expires”值也会影响到缓存。例如,指定Expires值为一个早已过去的时间,那么访问此网时若重复在地址栏按回车,那么每次都会重复访问:

Expires: Fri, 31 Dec 1999 16:00:00 GMT

在ASP中,可以通过Response对象的Expires、ExpiresAbsolute属性控制Expires值;通过Response对象的CacheControl属性控制Cache-control的值,例如:

Response.ExpiresAbsolute = #2000-1-1# ‘ 指定绝对的过期时间,这个时间用的是服务器当地时间,会被自动转换为GMT时间Response.Expires = 20 ‘ 指定相对的过期时间,以分钟为单位,表示从当前时间起过多少分钟过期。Response.CacheControl = "no-cache"Expires值是可以通过在Internet临时文件夹中查看临时文件的属性看到的。

Apache 主机解决方案:

Apache 设置缓存可以通过 mod_headers 模块修改 cache-control 来实现。

header set cache-control "max-age="3600"。mod_expires 实例:

<Directory /opt>ExpiresActive OnExpiresDefault "accesss plus 3600 seconds" 如果是1秒,后面也是secondsExpiresByType application/octet-stream "accesss plus 1 months" 这是对特殊文件类型bin缓存1个月<FilesMatch ^data.swf$> 针对opt目录下data.swf设置Expire值ExpiresActive OnExpiresDefault "accesss plus 60 seconds"</FilesMatch></Directory>mod_headers 实例:

<Directory /opt>header set cache-control "max-age=3600"<FilesMatch ^data.swf$>header set cache-control "max-age=60"</FilesMatch></Directory><FilesMatch ".(flv|gif|jpg|jpeg|png|ico|swf|js|css|pdf)$">Header set Cache-Control "max-age=2592000"</FilesMatch>

Nginx 主机解决方案:

Nginx 的 ngx_http_headers_module 模块可以对 Cache-Control 头相关的东西进行配置,例如:

if ($request_uri ~* "^/$|^/search/.+/|^/company/.+/") {add_header Cache-Control max-age=3600;}if ($request_uri ~* "^/search-suggest/|^/categories/") {add_header Cache-Control max-age=86400;}expires 的设置方法,增加至主机 conf 文件中:

location ~ ..(gif|jpg|jpeg|png|bmp|swf)${expires 30d;}location ~ .(ico|gif|jpg|jpeg|png|bmp|swf)(?[0-9]+)?${expires max;break;}

通过 HTTP 的 META 设置 expires 和 cache-control 解决方案:

<meta http-equiv="Cache-Control" content="max-age=7200" /> <meta http-equiv="Expires" content="Mon, 18 Aug 2014 23:00:00 GMT" />expires 用于设定网页的过期时间,也可设置为:

<meta http-equiv="Cache-Control" CONTENT="no-cache"> <meta http-equiv="Expires" content="0" />

CSS 中图片、字体及 JS 的 max_age 解决方案:

background-image:url(sprite/bg.png?max_age=31536000&d=05231747)格式为?d=月日小时分钟,其他文件如此类推。

广告 广告

评论区