apache - 如何使浏览器缓存 Apache 上的静态内容,而不是在每个请求时检查新鲜度?

标签 apache mod-expires image-caching

如何让 Apache 上的静态内容{由浏览器缓存}而不是{{每个请求}检查新鲜度}?

我正在开发一个托管在 Apache 网络服务器上的网站。最近,我正在测试一些带有 header 的内容(针对不同类型内容的 Content-Type),并看到很多对图像的条件请求。示例:

200 /index.php?page=1234&action=list
304 /favicon.ico
304 /img/logo.png
304 /img/arrow.png
(etc.)

虽然图像文件是静态内容并由浏览器缓存,但每次用户打开链接到它们的页面时,都会有条件地请求它们,并向其发送“304 Not Modified”。这很好(传输的数据更少),但这意味着每次页面加载都会增加 20 多个请求(由于所有这些往返,页面加载时间更长,即使启用了 Keep-Alive 和管道传输)。

如何告诉浏览器保留现有文件而不检查更新版本?

编辑: 即使使用图标,mod_expires 方法也可以工作。

最佳答案

Expires Apache 中的模块解决了这个问题

a2enmod expires

它需要加载到服务器配置中,并在.htaccess(或服务器配置)中设置。

带有 Expires header,该资源仅在第一次请求时被请求。在到期日期之前,后续请求将从浏览器缓存中满足。在指定的时间到期并且需要该资源后,才再次请求该资源(有条件地 - 对于未更改的资源将返回 304)。在过期之前从缓存中清除它的唯一可靠方法是手动或强制刷新(通常是 Ctrl-F5)。 (如果资源同时发生变化,这可能会成为一个问题,但静态图像不会经常变化。)

# enable the directives - assuming they're not enabled globally
ExpiresActive on

# send an Expires: header for each of these mimetypes (as defined by server)
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"

# css may change a bit sometimes, so define shorter expiration
ExpiresByType text/css "access plus 1 days"

对于 favicon.ico,需要做更多的工作(Apache 通常无法识别 Windows 图标文件,并将其作为默认文本/纯文本发送)。

# special MIME type for icons - see http://www.iana.org/assignments/media-types/image/vnd.microsoft.icon
AddType image/vnd.microsoft.icon .ico
# now we have icon MIME type, we can use it
# my favicon doesn't change much
ExpiresByType image/vnd.microsoft.icon "access plus 3 months"

瞧,It Works™!

关于apache - 如何使浏览器缓存 Apache 上的静态内容,而不是在每个请求时检查新鲜度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/447014/

相关文章:

php - htaccess 中的点给出 500 内部错误

linux - 一个子进程可以处理多少个连接?

asp.net - 迁移的 Web 表单应用程序 .NET 2.0 -> 3.5,新基础架构 - IE 6 中不缓存图像

asp.net-web-api - 缓存从 Web api 服务返回的图像

php - Web 服务器上的 Ldap 连接

php - Apache 重写 : file not found

css - IE7 不通过 SSL 缓存 CSS 图像

.htaccess - 如何设置缓存修改后过期呢?

apache - mod_expires 未在 JPEG 图像上设置缓存控制 header