Debian Apache 缓存机制优化指南
一 启用与准备
二 核心配置示例
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheEnable disk /
CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheDirLevels 2
CacheDirLength 1
CacheDefaultExpire 3600
CacheMaxExpire 86400
CacheMinExpire 600
# 可按需调整:仅缓存特定类型
CacheableMimeType text/html text/css application/javascript
# 提升并发写入安全与命中率
CacheLockOnPost On
CacheLockPath /tmp/mod_cache_lock
CacheLockMaxAge 5
# 视业务而定:忽略查询串、忽略 Set-Cookie(谨慎,确保无用户态差异)
CacheIgnoreQueryString On
CacheIgnoreHeaders Set-Cookie
# 可选:允许缓存带私有标记的响应(谨慎评估)
# CacheStorePrivateFiles On
</IfModule>
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 week"
ExpiresByType text/html "access plus 1 week"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/svg+xml "access plus 1 month"
</IfModule>
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
<IfModule mod_headers.c>
# 对静态资源设置强缓存
<FilesMatch "\.(css|js|jpe?g|png|svg|woff2?|ico)$">
Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>
</IfModule>
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
三 按内容类型的最佳实践
| 资源类型 | 建议服务器端缓存 | 建议浏览器缓存 | 备注 |
|---|---|---|---|
| HTML(动态) | 视页面可缓存性使用 CacheEnable disk;必要时配合 Vary | max-age=604800(1周) 或协商缓存 | 若含用户态信息,避免缓存或仅做短 TTL |
| CSS/JS | 可缓存;建议配合文件名哈希 | max-age=31536000(1年)+ immutable | 变更时通过文件名变更失效 |
| 图片/字体 | 可缓存 | max-age=31536000(1年) | 使用 Cache-Control: public |
| API/JSON(动态) | 通常不做页面级缓存 | 依据 ETag/Last-Modified 协商缓存 | 或使用 Cache-Control: no-store 保护隐私 |
| 带 Set-Cookie 的响应 | 谨慎缓存;必要时仅缓存 public 片段 | 视业务决定是否缓存 | 可用 CacheIgnoreHeaders Set-Cookie 但需评估副作用 |
四 验证与监控
五 进阶与注意事项