在 CentOS 上配置 Apache2 的缓存可以通过使用 Apache 的模块 mod_cache 和 mod_cache_disk 来实现。以下是一个基本的步骤指南:
首先,确保你已经安装了 Apache 和相关的模块。你可以使用以下命令来安装:
sudo yum install httpd mod_cache mod_cache_disk
启用 mod_cache 和 mod_cache_disk 模块:
sudo systemctl enable httpd
sudo systemctl start httpd
sudo systemctl status httpd
然后,启用缓存模块:
sudo sed -i 's/#LoadModule cache_module modules\/mod_cache.so/LoadModule cache_module modules\/mod_cache.so/' /etc/httpd/conf/httpd.conf
sudo sed -i 's/#LoadModule cache_disk_module modules\/mod_cache_disk.so/LoadModule cache_disk_module modules\/mod_cache_disk.so/' /etc/httpd/conf/httpd.conf
编辑 Apache 配置文件 /etc/httpd/conf/httpd.conf 或创建一个新的配置文件在 /etc/httpd/conf.d/ 目录下,例如 cache.conf。
sudo vi /etc/httpd/conf.d/cache.conf
添加以下配置:
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheEnable disk /mycache
CacheRoot "/var/cache/httpd/mycache"
CacheDirLevels 2
CacheDirLength 1
CacheDefaultExpire 3600
</IfModule>
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/html "access plus 1 hour"
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
</IfModule>
你可以在特定的 <Location> 或 <Directory> 块中配置缓存规则。例如:
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
<Location "/static">
CacheEnable disk /mycache
CacheIgnoreHeaders Set-Cookie
CacheIgnoreNoLastMod On
CacheMaxExpire 86400
CacheMinExpire 300
</Location>
</IfModule>
</IfModule>
保存配置文件并重启 Apache 以应用更改:
sudo systemctl restart httpd
你可以通过访问你的网站并检查响应头来验证缓存是否正常工作。例如,使用 curl 命令:
curl -I http://yourwebsite.com/static/image.jpg
你应该能看到 Cache-Control 头信息,表明缓存正在生效。
通过以上步骤,你可以在 CentOS 上配置 Apache2 的缓存。根据你的具体需求,你可以进一步调整缓存设置和规则。