【问题标题】:Set HTTP Caching Expiration, Recommended by Google PageSpeed设置 HTTP 缓存过期,由 Google PageSpeed 推荐
【发布时间】:2011-02-10 05:30:02
【问题描述】:

我使用 Google 的 PageSpeed 在我的网站上进行了测试,它建议我“利用浏览器缓存”并提供以下资源:

http://code.google.com/speed/page-speed/docs/caching.html#LeverageBrowserCaching

此资源从未解释如何实际更改我的 http 标头的到期日期。我是否通过 .htaccess 执行此操作?我想尽可能长时间地设置缓存(不违反 Google 的最长一年政策)。

任何关于推荐设置的建议(用于自定义 php 驱动的社交网络社区)将不胜感激。

【问题讨论】:

    标签: php .htaccess caching pagespeed


    【解决方案1】:

    在您的根目录的 .htaccess 中:

    <IfModule mod_expires.c>
      ExpiresActive On
      ExpiresDefault "access plus 1 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/x-javascript "access plus 216000 seconds"
      ExpiresByType text/html "access plus 600 seconds"
      ExpiresByType application/xhtml+xml "access plus 600 seconds"
    </IfModule>
    

    然后跟随:

    <IfModule mod_headers.c>
    <FilesMatch "\\.(ico|jpe?g|png|gif|swf)$">
    Header set Cache-Control "max-age=2692000, public"
    </FilesMatch>
    <FilesMatch "\\.(css)$">
    Header set Cache-Control "max-age=2692000, public"
    </FilesMatch>
    <FilesMatch "\\.(js)$">
    Header set Cache-Control "max-age=216000, private"
    </FilesMatch>
    <FilesMatch "\\.(x?html?|php)$">
    Header set Cache-Control "max-age=600, private, must-revalidate"
    </FilesMatch>
    Header unset ETag
    Header unset Last-Modified
    </IfModule>
    

    这是我在我管理的每个属性上使用的完全相同的代码,并为我(和 PageSpeed)提供了最令人满意的结果。有人可能会争论具体的规则,这就是为什么我说它满足,但它肯定满足 PageSpeed。

    【讨论】:

    • 这取决于你所说的“很多条件”是什么意思。条件必须由 Web 服务器对每个 HTTP 请求进行处理,因此如果您考虑 65,000 多个条件,那么这肯定不是一个好主意
    • 只是小费。您可以只写“访问加 1 年”甚至更复杂的指令,例如“访问加 1 个月 15 天 2 小时”,这比几秒钟更容易阅读和维护。
    • @GeneQ,该提示 +1。我习惯于 unix 时间戳,可能这就是我在规则中使用秒数的原因。
    • 另一种设置过期时间的方法,ExpiresByType application/javascript A604800 [A604800代表访问时间+604800秒]
    • 对于css,Header set Cache-Control "max-age=2692000, public"是否接管ExpiresByType text/css "access plus 604800 seconds"?两者应该是相同的值吗?
    【解决方案2】:

    htaccess 和 php 都可以。通常,您不想强制缓存实际的 html,因为它是动态数据库驱动的内容(如果需要,可以使用 header() php 函数完成)。您要缓存的是外部 css & javascript 和图像文件。

    在此处查看 .htaccess 解决方案:http://www.askapache.com/htaccess/apache-speed-expires.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-17
      • 2011-10-31
      • 2019-07-23
      • 2016-12-05
      • 1970-01-01
      • 2012-03-18
      相关资源
      最近更新 更多