apache通过mod_expires或mod_headers模块设置缓存,优先用cache-control;需启用对应模块并配置expiresbytype或header set指令,按资源类型差异化设置max-age等参数,禁用动态内容缓存。

Apache 为不同类型资源设置缓存周期,核心是通过 mod_expires 或 mod_headers 模块,在响应中注入合适的 Cache-Control 或 Expires 头。推荐优先使用 Cache-Control(更现代、语义清晰),并按 MIME 类型或文件扩展名区分策略。
启用必要模块
确保以下模块已加载(在 httpd.conf 或 apache2.conf 中):
LoadModule expires_module modules/mod_expires.soLoadModule headers_module modules/mod_headers.so
重启 Apache 生效。若用 .htaccess,还需确认对应目录允许 AllowOverride All 或至少包含 FileInfo 和 Indexes。
按 MIME 类型配置缓存(推荐方式)
使用 ExpiresByType 直接关联标准 MIME 类型,语义明确且不依赖文件后缀:
- 图片类:
ExpiresByType image/jpeg "access plus 1 year" - CSS/JS:
ExpiresByType text/css "access plus 1 month"、ExpiresByType application/javascript "access plus 1 month" - 字体:
ExpiresByType font/woff2 "access plus 1 year" - WebAssembly:
ExpiresByType application/wasm "access plus 1 week"
配合 ExpiresActive On 启用,并用 ExpiresDefault 设兜底值(如 "access plus 1 day")。
Apache 2.4.62 官方 tar.gz 源码包是 Linux 及类 Unix 系统构建 Web 服务器的核心基础。通过源码编译安装,开发者能够灵活定制模块、优化性能并精准控制安装路径,满足多样化的业务需求。
用 Cache-Control 精确控制行为
比 Expires 更灵活,支持 public、immutable、no-store 等指令:
- 静态资源(图片/CSS/JS/字体):
Header set Cache-Control "public, immutable, max-age=31536000" - HTML 页面(避免缓存):
Header set Cache-Control "no-cache, must-revalidate, max-age=0" - API 响应(如 JSON):
Header set Cache-Control "no-store"(防止敏感数据被缓存)
可结合 <filesmatch></filesmatch> 按扩展名匹配,例如:
<filesmatch><br> Header set Cache-Control "public, immutable, max-age=31536000"<br></filesmatch>
禁用动态内容缓存
HTML、PHP 输出、JSON 接口等不应长期缓存。即使服务端返回了 Content-Type: text/html,也要显式覆盖:
- 匹配路径:
<locationmatch> Header set Cache-Control "no-store" </locationmatch> - 匹配类型(Apache 2.4+):
<if m> Header set Cache-Control "no-store" </if>
验证时用 curl -I https://yoursite.com/test.jpg 或浏览器开发者工具的 Network 面板,检查响应头是否含预期的 Cache-Control 或 Expires 字段。










