一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

怎样配置 Apache 为不同资源类型指定缓存周期

时间:2026-07-11 09:00:57 编辑:袖梨 来源:一聚教程网

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

Apache 为不同类型资源设置缓存周期,核心是通过 mod_expiresmod_headers 模块,在响应中注入合适的 Cache-ControlExpires 头。推荐优先使用 Cache-Control(更现代、语义清晰),并按 MIME 类型或文件扩展名区分策略。

启用必要模块

确保以下模块已加载(在 httpd.confapache2.conf 中):

  • LoadModule expires_module modules/mod_expires.so
  • LoadModule headers_module modules/mod_headers.so

重启 Apache 生效。若用 .htaccess,还需确认对应目录允许 AllowOverride All 或至少包含 FileInfoIndexes

按 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")。

用 Cache-Control 精确控制行为

Expires 更灵活,支持 publicimmutableno-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 ".(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>
  • 匹配类型(Apache 2.4+):<If "%{CONTENT_TYPE} =~ m#^application/json#i"> Header set Cache-Control "no-store" </If>

验证时用 curl -I https://yoursite.com/test.jpg 或浏览器开发者工具的 Network 面板,检查响应头是否含预期的 Cache-ControlExpires 字段。

热门栏目