apache mod_expires是设置浏览器缓存最稳妥、最兼容的方式,需先启用mod_expires和mod_headers模块,再按mime类型用expiresbytype精准设缓存(如图片1年、css/js1个月),并用mod_headers补全cache-control与immutable语义,最后通过curl或devtools验证响应头。

Apache 的 mod_expires 是设置浏览器缓存最稳妥、最广泛兼容的方式。它不依赖文件名或路径,而是依据响应头中的 MIME 类型 精准控制,配合 mod_headers 补全现代语义(如 immutable),就能实现高效又可控的静态资源缓存。
先确认模块已启用
很多配置失效,根源是模块根本没加载——ExpiresActive On 在未启用模块时会静默忽略。
- 运行
apachectl -M | grep expires和apachectl -M | grep headers,确认两模块都列出 - 若未启用:Debian/Ubuntu 执行
a2enmod expires headers;CentOS/RHEL 或源码安装则需在httpd.conf中取消这两行的注释:LoadModule expires_module modules/mod_expires.soLoadModule headers_module modules/mod_headers.so - 重启服务:
sudo systemctl restart apache2(或sudo apachectl graceful)
按 MIME 类型设缓存,不是按后缀
用 ExpiresByType 而非 ExpiresDefault 或 <filesmatch></filesmatch>,因为真实 Content-Type 才决定浏览器行为(例如 CDN 回源或 PHP 输出图片时,扩展名可能失真)。
Apache 2.4.62 官方 tar.gz 源码包是 Linux 及类 Unix 系统构建 Web 服务器的核心基础。通过源码编译安装,开发者能够灵活定制模块、优化性能并精准控制安装路径,满足多样化的业务需求。
- 图片类(极少变动):
ExpiresByType image/jpeg "access plus 1 year"ExpiresByType image/png "access plus 1 year"ExpiresByType image/webp "access plus 1 year"ExpiresByType image/x-icon "access plus 1 year" - CSS 与 JS(带哈希版本号时可用较长时间):
ExpiresByType text/css "access plus 1 month"ExpiresByType application/javascript "access plus 1 month" - 动态内容必须排除:
ExpiresByType text/html "access plus 0 seconds"ExpiresByType application/json "access plus 0 seconds"
补上 Cache-Control,尤其 immutable
Expires 是 HTTP/1.0 兼容字段,现代浏览器以 Cache-Control: max-age= 为准。且仅设 max-age 不足以阻止条件请求(如 F5 触发的 If-None-Match),加 immutable 才真正“强缓存”。
- 对图片等不可变资源:
<ifmodule mod_headers.c><br> <filesmatch><br> Header set Cache-Control "public, immutable, max-age=31536000"<br> </filesmatch><br></ifmodule> - 对 CSS/JS(1 个月对应 2592000 秒):
<filesmatch><br> Header set Cache-Control "public, max-age=2592000"<br></filesmatch>
验证是否生效
别只看配置写了没,要查真实响应头:
- 命令行:
curl -I https://yoursite.com/style.css,检查是否同时存在:Expires: [未来时间]Cache-Control: public, max-age=..., immutable - 浏览器 DevTools → Network → 点开某个图片/CSS → Headers → Response Headers
- 刷新页面后观察该资源是否返回
200 (from disk cache)或304 Not Modified,而非始终200 OK










