php - 设置 HTTP 缓存过期,由 Google PageSpeed 推荐

标签 php .htaccess caching pagespeed

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

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

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

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

最佳答案

在你的 root 的 .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>

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

关于php - 设置 HTTP 缓存过期,由 Google PageSpeed 推荐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2676744/

相关文章:

php - 使用 php 从非公共(public) html 文件夹下载文件

apache - htaccess - 当请求的 URL 是我系统上的文件夹时,重写规则不起作用

python - Django 缓存丢失 key

javascript - 我的 javascript 无法在浏览器中缓存

php - 在 PHP 中获取唯一的 worker/thread/process/request ID

php - 如何为 html 和 php 使用外部 css 样式表

php - 使用 php 代码调用 MYSQL CREATE VIEW?

.htaccess - mod重写删除分页重复内容

php - Apache GZip 无法使用文本文件和 js 文件?

mysql - 缓存与数据库查询