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图标文件,并将其作为默认文本/ plain发送)。
# 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™!