【问题标题】:leverage browser caching利用浏览器缓存
【发布时间】:2011-10-15 14:04:14
【问题描述】:

我想利用浏览器缓存来提高页面速度。听起来 max-age 和 last-modified 是不错的选择,但我不清楚如何确定应该为它实现哪些文件。一般来说,我对如何实际执行此操作以及代码在我的 htaccess 中的外观感到困惑。我想我希望获得一些更明确的帮助或展示一些示例。或者,也许有人可以指导我上一个像我这样的新手可以理解的课程/教程,但我没有找到任何运气。任何了解 max-age 和 last-modified 并且可以帮助告诉我如何做到这一点的人的任何帮助将不胜感激。我真的很迷茫,会花钱请人来帮助我。谢谢。

【问题讨论】:

    标签: pagespeed


    【解决方案1】:

    在这里搜索 SO 会返回一些很好的信息 - 例如 Leverage browser caching - 但无论如何......

    发件人:http://www.samaxes.com/2011/05/improving-web-performance-with-apache-and-htaccess/

    第一次访问您的页面的访问者会发出多个 HTTP 请求来下载您的所有站点文件,但通过使用 ExpiresCache-Control 标头,您可以使这些文件可缓存。这样可以避免在后续页面查看时发出不必要的 HTTP 请求。

    借助 mod_expiresmod_headers 模块,Apache 启用了这些标头。

    mod_expires 模块控制服务器响应中Expires HTTP 标头和Cache-Control HTTP 标头的max-age 指令的设置。

    要修改max-age以外的Cache-Control指令,可以使用mod_headers模块。

    mod_headers 模块提供指令来控制和修改 HTTP 请求和响应标头。标题可以合并、替换或删除。

    Expires标头设置规则:

    # BEGIN Expire headers
    <ifModule mod_expires.c>
      ExpiresActive On
      ExpiresDefault "access plus 5 seconds"
      ExpiresByType image/x-icon "access plus 2592000 seconds"
      ExpiresByType image/jpeg "access plus 2592000 seconds"
      ExpiresByType image/png "access plus 2592000 seconds"
      ExpiresByType image/gif "access plus 2592000 seconds"
      ExpiresByType application/x-shockwave-flash "access plus 2592000 seconds"
      ExpiresByType text/css "access plus 604800 seconds"
      ExpiresByType text/javascript "access plus 216000 seconds"
      ExpiresByType application/javascript "access plus 216000 seconds"
      ExpiresByType application/x-javascript "access plus 216000 seconds"
      ExpiresByType text/html "access plus 600 seconds"
      ExpiresByType application/xhtml+xml "access plus 600 seconds"
    </ifModule>
    # END Expire headers
    

    Cache-Control 标头设置规则:

    # BEGIN Cache-Control Headers
    <ifModule mod_headers.c>
      <filesMatch "\.(ico|jpe?g|png|gif|swf)$">
        Header set Cache-Control "public"
      </filesMatch>
      <filesMatch "\.(css)$">
        Header set Cache-Control "public"
      </filesMatch>
      <filesMatch "\.(js)$">
        Header set Cache-Control "private"
      </filesMatch>
      <filesMatch "\.(x?html?|php)$">
        Header set Cache-Control "private, must-revalidate"
      </filesMatch>
    </ifModule>
    # END Cache-Control Headers
    

    注意:不需要使用Cache-Control 标头设置max-age 指令,因为它已经由mod_expires 模块设置。

    must-revalidate 意味着一旦响应变得陈旧,就必须重新验证;这并不意味着每次都必须检查。

    更多信息在这里:http://www.mnot.net/cache_docs/
    来自谷歌:http://code.google.com/speed/page-speed/docs/caching.html
    和雅虎:http://developer.yahoo.com/performance/rules.html#expires

    【讨论】: