Apache 中的Expires模块解决了这个问题
a2enmod expires
它需要在服务器配置中加载,并在.htaccess
(或在服务器配置中)进行设置。
使用Expires标头,仅在第一次请求资源。在到期日期之前,后续请求会从浏览器缓存中完成。在指定的时间到期并且需要资源后,才再次请求它(有条件 - 将返回 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™!