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。
使用 ExpiresByType 直接关联标准 MIME 类型,语义明确且不依赖文件后缀:
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType text/css "access plus 1 month"、ExpiresByType application/javascript "access plus 1 month"
ExpiresByType font/woff2 "access plus 1 year"
ExpiresByType application/wasm "access plus 1 week"
配合 ExpiresActive On 启用,并用 ExpiresDefault 设兜底值(如 "access plus 1 day")。
比 Expires 更灵活,支持 public、immutable、no-store 等指令:
Header set Cache-Control "public, immutable, max-age=31536000"
Header set Cache-Control "no-cache, must-revalidate, max-age=0"
Header set Cache-Control "no-store"(防止敏感数据被缓存)可结合 <FilesMatch> 按扩展名匹配,例如:
<FilesMatch ".(jpg|png|gif|css|js|woff2)$"><br> Header set Cache-Control "public, immutable, max-age=31536000"<br></FilesMatch>
HTML、PHP 输出、JSON 接口等不应长期缓存。即使服务端返回了 Content-Type: text/html,也要显式覆盖:
<LocationMatch "/api/.*.json$"> Header set Cache-Control "no-store" </LocationMatch>
<If "%{CONTENT_TYPE} =~ m#^application/json#i"> Header set Cache-Control "no-store" </If>
验证时用 curl -I https://yoursite.com/test.jpg 或浏览器开发者工具的 Network 面板,检查响应头是否含预期的 Cache-Control 或 Expires 字段。