Apache实现静态资源强缓存需启用mod_expires和mod_headers模块,按MIME类型用ExpiresByType精准设过期时间(如图片1年、CSS/JS1个月),禁用HTML等动态内容缓存,并用mod_headers补充Cache-Control与immutable头,最后通过curl或DevTools验证响应头。
启用 mod_expires 是 apache 实现静态资源长效缓存的关键一步,但光开模块远远不够——必须配合 mime 类型精准控制、禁用动态内容缓存,并补充现代 cache-control 头,才能真正提升加载速度和减少服务器压力。
确认并启用 mod_expires 和 mod_headers 模块
这两个模块缺一不可:mod_expires 生成 Expires 和基础 max-age,mod_headers 用于设置更精细的 Cache-Control(比如 immutable)。
- 运行
apachectl -M | grep -E 'expires|headers',检查是否已加载。看到expires_module (shared)和headers_module (shared)表示就绪 - 若未启用,在主配置文件(
/etc/apache2/apache2.conf或/etc/httpd/conf/httpd.conf)中取消以下两行注释:LoadModule expires_module modules/mod_expires.soLoadModule headers_module modules/mod_headers.so - Debian/Ubuntu 系统可直接执行:
a2enmod expires headers - 重启服务生效:
systemctl restart apache2(或httpd)
按 MIME 类型设置强缓存策略(不靠文件后缀)
用 ExpiresByType 比 FilesMatch 更可靠,它依据响应头中的 Content-Type 判断,避免因重写、CDN 或 MIME 配置偏差导致误配。
- 在虚拟主机配置或
.htaccess中添加:<IfModule mod_expires.c>ExpiresActive On# 图片类长效缓存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 推荐 1 个月;若带哈希名(如 app.abc123.js),可升为 1 年ExpiresByType text/css "access plus 1 month"ExpiresByType application/javascript "access plus 1 month"# 字体与 WASMExpiresByType font/woff2 "access plus 1 year"ExpiresByType application/wasm "access plus 1 week"# 显式禁用 HTML、JSON、XML 等动态内容ExpiresByType text/html "access plus 0 seconds"ExpiresByType application/json "access plus 0 seconds"ExpiresByType application/xml "access plus 0 seconds"# 兜底:未匹配类型一律不缓存ExpiresDefault "access plus 0 seconds"</IfModule>
用 mod_headers 补充 Cache-Control 提升兼容性
仅靠 Expires 已不够——现代浏览器优先信任 Cache-Control: max-age,且 immutable 能彻底跳过条件请求(适用于哈希命名资源)。
- 确保
mod_headers已启用(见上一步) - 添加如下配置:
<IfModule mod_headers.c><FilesMatch "\.(jpg|jpeg|png|webp|gif|ico|svg|woff2)$">Header set Cache-Control "public, max-age=31536000, immutable"</FilesMatch><FilesMatch "\.(css|js)$">Header set Cache-Control "public, max-age=2592000"</FilesMatch></IfModule> - 注意:不要对 CSS/JS 加
immutable,除非文件名含哈希;否则更新后用户可能无法获取新版本
验证缓存是否真正生效
配置完不验证 = 白配。重点看响应头是否同时包含 Expires 和 Cache-Control,且状态码体现缓存命中。
- 命令行验证:
curl -I https://yoursite.com/style.css,检查输出中是否有:Expires: [未来时间]Cache-Control: public, max-age=2592000 - 浏览器验证:打开 DevTools → Network → 刷新页面 → 点击某个 JS 或图片 → 查看 Headers → Response Headers
- 首次请求应为
200 OK,二次请求理想状态是200 (from disk cache)(强缓存命中)或304 Not Modified(协商缓存) - 修改配置后记得重载:
systemctl reload apache2(比 restart 更轻量)


















