下面按常见用法给你讲「Apache2 缓存配置」的几种方式,从简单到进阶,你可以按需求选。
适合:静态资源(css、js、图片等)
sudo a2enmod expires
sudo a2enmod headers
sudo systemctl restart apache2
在虚拟主机或 .htaccess 中:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 7 days"
ExpiresByType application/javascript "access plus 7 days"
ExpiresByType image/jpeg "access plus 30 days"
ExpiresByType image/png "access plus 30 days"
</IfModule>
<IfModule mod_headers.c>
<FilesMatch "\.(css|js|jpg|png|gif)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>
</IfModule>
适合:反向代理 / 动态页面加速
sudo a2enmod cache
sudo a2enmod cache_disk
sudo systemctl restart apache2
<IfModule mod_cache.c>
CacheEnable disk /
CacheRoot /var/cache/apache2/mod_cache_disk
CacheDirLevels 2
CacheDirLength 1
CacheDefaultExpire 3600
</IfModule>
创建缓存目录:
sudo mkdir -p /var/cache/apache2/mod_cache_disk
sudo chown -R www-data:www-data /var/cache/apache2/mod_cache_disk
如果你用 Apache 做代理:
ProxyPass / http://127.0.0.1:8080/
ProxyPassReverse / http://127.0.0.1:8080/
CacheEnable disk /
CacheIgnoreHeaders Set-Cookie
CacheDisable /admin
CacheDisable /api
或在 PHP 中:
header("Cache-Control: no-store, no-cache, must-revalidate");
curl -I http://your-site.com/style.css
看到:
Cache-Control: max-age=604800
Expires: ...
就说明成功。
| 场景 | 推荐 |
|---|---|
| 普通网站 | Expires + Headers |
| API | 不缓存 |
| 高并发 | mod_cache + 反向代理 |
如果你告诉我:
我可以给你直接可用的配置模板。