centos

CentOS Apache缓存策略

小樊
32
2025-12-17 13:14:07
栏目: 智能运维

CentOS 上 Apache 缓存策略实践指南

一 缓存类型与适用场景

二 启用模块与基础检查

# 示例:/etc/httpd/conf.modules.d/00-cache.conf
LoadModule cache_module modules/mod_cache.so
LoadModule disk_cache_module modules/mod_disk_cache.so
# LoadModule mem_cache_module modules/mod_mem_cache.so   # 可选:内存缓存
LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
# LoadModule file_cache_module modules/mod_file_cache.so   # 可选:文件句柄/内存映射
sudo apachectl configtest
sudo systemctl restart httpd

三 配置方案示例

<IfModule mod_cache.c>
  <IfModule mod_disk_cache.c>
    CacheRoot   /var/cache/httpd/proxy
    CacheEnable  disk  /
    CacheDirLevels  2
    CacheDirLength  1
    CacheSize      256000   # 单位 KB,示例约 250 MB
    CacheMaxFileSize  1048576 # 1 MB
    CacheMinFileSize  10

    # 过期策略:无显式过期时使用的默认与上限
    CacheDefaultExpire  3600
    CacheMaxExpire      86400

    # 计算过期:基于 Last-Modified 的启发式因子
    CacheLastModifiedFactor 0.5

    # 容错与覆盖:忽略客户端 no-cache/no-store;允许无 Last-Modified 的响应进入候选
    CacheIgnoreCacheControl On
    CacheIgnoreNoLastMod    On

    # 可选:即使客户端中断,也尽量完成缓存写入(提升命中)
    CacheForceCompletion 80
  </IfModule>
</IfModule>
<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresDefault "access plus 1 hour"
  ExpiresByType text/css                  "access plus 1 year"
  ExpiresByType application/javascript    "access plus 1 year"
  ExpiresByType image/jpeg               "access plus 1 year"
  ExpiresByType image/png                "access plus 1 year"
  ExpiresByType image/gif                "access plus 1 year"
  ExpiresByType image/svg+xml             "access plus 1 year"
  ExpiresByType font/woff2                "access plus 1 year"
</IfModule>

<IfModule mod_headers.c>
  # 对匹配的资源补充 Cache-Control(可与 Expires 叠加)
  <FilesMatch "\.(css|js|jpe?g|png|gif|svg|woff2)$">
    Header set Cache-Control "public, max-age=31536000, immutable"
  </FilesMatch>
</IfModule>
# 注意:变更文件后需重启 httpd 才会生效
LoadModule file_cache_module modules/mod_file_cache.so

CacheFile /var/www/html/index.html
CacheFile /var/www/html/static/logo.png

# 或使用内存映射(谨慎:不跟踪内存占用,子进程复制可能导致内存放大)
# MMapFile /var/www/html/index.html
sudo apachectl configtest
sudo systemctl restart httpd
curl -I https://your-domain/static/app.js
# 期望看到:Cache-Control: public, max-age=31536000 或 Expires: <未来时间>

四 关键指令与行为要点

五 验证与运维建议

0
看了该问题的人还看了