在 Linux 上的 Apache(通常是 httpd 或 apache2)启用缓存,常见有几种方式,下面按使用场景给你说明,最常用的是 mod_cache(服务端缓存) 和 浏览器缓存(Expires / Cache-Control)。
# CentOS / RHEL
sudo yum install mod_cache mod_cache_disk
sudo httpd -M | grep cache
# Ubuntu / Debian
sudo a2enmod cache
sudo a2enmod cache_disk
sudo systemctl restart apache2
编辑配置文件(如 /etc/httpd/conf.d/cache.conf 或 /etc/apache2/conf-available/cache.conf):
<IfModule mod_cache.c>
CacheEnable disk /
CacheRoot /var/cache/apache2
CacheDirLevels 2
CacheDirLength 1
CacheDefaultExpire 3600
CacheMaxExpire 86400
CacheIgnoreHeaders Set-Cookie
</IfModule>
创建缓存目录:
sudo mkdir -p /var/cache/apache2
sudo chown -R apache:apache /var/cache/apache2 # CentOS
sudo chown -R www-data:www-data /var/cache/apache2 # Ubuntu
重启 Apache:
sudo systemctl restart apache2
# 或
sudo systemctl restart httpd
✅ 适合:动态页面、反向代理、API 缓存
# Ubuntu
sudo a2enmod expires
sudo a2enmod headers
# CentOS
sudo yum install mod_expires mod_headers
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 7 days"
ExpiresByType image/jpeg "access plus 30 days"
ExpiresByType image/png "access plus 30 days"
ExpiresByType application/javascript "access plus 7 days"
</IfModule>
<IfModule mod_headers.c>
Header set Cache-Control "max-age=604800, public"
</IfModule>
✅ 适合:图片、CSS、JS 等静态资源
CacheEnable disk /
ProxyPass / http://backend/
ProxyPassReverse / http://backend/
curl -I http://localhost/
看是否有:
Age:
X-Cache: HIT
Cache-Control:
CacheIgnoreURLSessionIdentifiers如果你能告诉我:
我可以给你一份精准可用的配置。