Pis*_*3.0 43 apache mod-expires image-caching
我怎样才能获得Apache上的静态内容{被浏览器缓存}而不是{检查新鲜度{每次请求}}?
我正在Apache webserver上托管的网站上工作.最近,我正在使用标题(针对不同类型的内容的Content-Type)进行测试,并看到了很多对图像的条件请求.例:
200 /index.php?page=1234&action=list
304 /favicon.ico
304 /img/logo.png
304 /img/arrow.png
(etc.)
Run Code Online (Sandbox Code Playgroud)
虽然图像文件是静态内容并且由浏览器缓存,但每次用户打开链接到它们的页面时,它们都是有条件请求的,它们发送"304 Not Modified".这很好(传输的数据较少),但这意味着每次页面加载会产生20多个请求(由于所有这些往返行程导致页面加载时间更长,即使启用了Keep-Alive和流水线操作).
如何告诉浏览器保留现有文件而不检查更新版本?
编辑:mod_expires方法工作,即使使用favicon.
Pis*_*3.0 57
Apache中的Expires模块解决了这个问题 - 它需要在服务器配置中加载,并在.htaccess
(或在服务器配置中)进行设置.
使用Expires标头,仅在第一次请求资源.在到期日期之前,后续请求将从浏览器缓存中完成.在指定的时间到期并且需要资源之后,再次请求它(有条件地 - 对于未更改的资源将返回304).在缓存过期之前从缓存中清除它的唯一可靠方法是手动或通过强制刷新(通常是Ctrl-F5).(如果资源在此期间发生变化,这可能是个问题,但静态图像不会经常变化.)
a2enmod expires
Run Code Online (Sandbox Code Playgroud)
对于favicon.ico,需要做更多工作(Apache通常无法识别Windows图标文件,并将其作为默认文本/ plain发送).
# 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"
Run Code Online (Sandbox Code Playgroud)
瞧,It Works™!
Mar*_*aio 25
随着filesMatch
指令,而不是ExpiresByType
,您可以将Content-Type
通过匹配subtype
(例如image/*
),而不是列出每个type/subtype
对,而不是subtype
(例如image/jpeg
,image/png
).
#Set caching on image files for 11 months
<filesMatch "\.(ico|gif|jpg|png)$">
ExpiresActive On
ExpiresDefault "access plus 11 month"
Header append Cache-Control "public"
</filesMatch>
Run Code Online (Sandbox Code Playgroud)
根据这篇谷歌文章,我的过期时间不超过1年(access plus 11 month
),并添加Cache-Control "public"
了启用Firefox的HTTPS缓存.
对于CSS和JS,Google建议有效期为1周.
<filesMatch "\.(css|js)$">
ExpiresActive On
ExpiresDefault "access plus 1 week"
Header append Cache-Control "public"
</filesMatch>
Run Code Online (Sandbox Code Playgroud)