在 Ubuntu 上使用 Apache2 设置缓存,通常分为几种场景。下面按最常用、最实用的方式给你说明。
Apache 提供了一套缓存模块,常用组合是:
mod_cachemod_cache_disk(磁盘缓存)mod_expires(设置浏览器缓存时间)mod_headers(控制缓存头)sudo a2enmod cache
sudo a2enmod cache_disk
sudo a2enmod expires
sudo a2enmod headers
sudo systemctl restart apache2
编辑站点配置(例如 /etc/apache2/sites-available/000-default.conf):
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/html
# 开启 Expires
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 30 days"
ExpiresByType image/png "access plus 30 days"
ExpiresByType text/css "access plus 7 days"
ExpiresByType application/javascript "access plus 7 days"
</IfModule>
# 缓存头
<IfModule mod_headers.c>
<FilesMatch "\.(jpg|png|css|js)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>
</IfModule>
</VirtualHost>
重启 Apache:
sudo systemctl restart apache2
适合缓存动态页面或上游内容。
sudo mkdir -p /var/cache/apache2/mod_cache_disk
sudo chown -R www-data:www-data /var/cache/apache2
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/html
CacheEnable disk "/"
CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheDirLevels 2
CacheDirLength 1
CacheDefaultExpire 3600
<Location "/">
CacheEnable disk
CacheHeader on
CacheIgnoreNoLastMod On
</Location>
</VirtualHost>
重启:
sudo systemctl restart apache2
<Location "/api/">
CacheDisable on
</Location>
或:
Header set Cache-Control "no-store"
curl -I http://localhost/image.png
应看到:
Cache-Control: max-age=604800
Expires: ...
restart apache2Set-CookieCache-Control: no-cache| 场景 | 推荐方式 |
|---|---|
| 静态资源 | mod_expires + mod_headers |
| 动态页面 | mod_cache_disk |
| API | 禁用缓存 |
如果你能告诉我:
我可以给你更精确的配置。