温馨提示×

如何在 CentOS 上配置 Apache2 的缓存

小樊
37
2025-11-17 21:35:36
栏目: 智能运维

在 CentOS 上配置 Apache2 的缓存可以通过使用 Apache 的模块 mod_cachemod_cache_disk 来实现。以下是一个基本的步骤指南:

1. 安装 Apache 和相关模块

首先,确保你已经安装了 Apache 和相关的模块。你可以使用以下命令来安装:

sudo yum install httpd mod_cache mod_cache_disk

2. 启用模块

启用 mod_cachemod_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

3. 配置缓存

编辑 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>

4. 配置缓存规则

你可以在特定的 <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>

5. 重启 Apache

保存配置文件并重启 Apache 以应用更改:

sudo systemctl restart httpd

6. 验证配置

你可以通过访问你的网站并检查响应头来验证缓存是否正常工作。例如,使用 curl 命令:

curl -I http://yourwebsite.com/static/image.jpg

你应该能看到 Cache-Control 头信息,表明缓存正在生效。

通过以上步骤,你可以在 CentOS 上配置 Apache2 的缓存。根据你的具体需求,你可以进一步调整缓存设置和规则。

0