在Apache2中设置缓存可以通过多种方式实现,包括使用模块和配置指令。以下是一些常见的方法来设置缓存:
启用模块:
首先,确保你已经启用了mod_cache
和mod_cache_disk
模块。你可以使用以下命令来启用它们:
sudo a2enmod cache
sudo a2enmod cache_disk
配置缓存:
编辑你的Apache配置文件(通常是/etc/apache2/apache2.conf
或/etc/apache2/sites-available/your-site.conf
),添加以下配置:
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheEnable disk /your-cache-path
CacheRoot "/your-cache-path"
CacheDirLevels 2
CacheDirLength 1
CacheIgnoreHeaders Set-Cookie
CacheIgnoreNoLastMod On
CacheDefaultExpire 3600
</IfModule>
</IfModule>
CacheEnable disk /your-cache-path
:启用磁盘缓存,并指定缓存路径。CacheRoot "/your-cache-path"
:指定缓存根目录。CacheDirLevels 2
和 CacheDirLength 1
:设置缓存目录的结构。CacheIgnoreHeaders Set-Cookie
:忽略Set-Cookie头,以便缓存静态内容。CacheDefaultExpire 3600
:设置默认缓存过期时间为3600秒(1小时)。重启Apache: 保存配置文件并重启Apache以应用更改:
sudo systemctl restart apache2
如果你只想设置静态内容的缓存过期时间,可以使用mod_expires
模块:
启用模块:
确保你已经启用了mod_expires
模块:
sudo a2enmod expires
配置缓存: 编辑你的Apache配置文件,添加以下配置:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/html "access plus 1 hour"
ExpiresByType image/jpeg "access plus 1 week"
ExpiresByType image/png "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
</IfModule>
ExpiresActive On
:启用Expires头。ExpiresByType
:为不同类型的文件设置缓存过期时间。重启Apache: 保存配置文件并重启Apache以应用更改:
sudo systemctl restart apache2
Varnish是一个高性能的反向代理和缓存服务器,可以与Apache一起使用:
安装Varnish:
sudo apt-get install varnish
配置Varnish:
编辑Varnish配置文件(通常是/etc/varnish/default.vcl
),添加以下配置:
backend default {
.host = "127.0.0.1";
.port = "80";
}
sub vcl_recv {
if (req.http.host ~ "your-domain.com") {
set req.http.x-redir = "http://" + req.http.host + req.http.x-redir;
set req.http.x-redir = regsub(req.http.x-redir, "https://", "");
return (synth(750, "Redirect to http"));
}
}
sub vcl_backend_response {
if (bereq.http.x-redir) {
set beresp.http.Location = req.http.x-redir;
set beresp.status = 301;
return (deliver);
}
}
重启Varnish: 保存配置文件并重启Varnish以应用更改:
sudo systemctl restart varnish
配置Apache: 编辑你的Apache配置文件,添加以下配置以将请求转发到Varnish:
<VirtualHost *:80>
ServerName your-domain.com
ProxyPass / http://127.0.0.1:6081/
ProxyPassReverse / http://127.0.0.1:6081/
</VirtualHost>
重启Apache: 保存配置文件并重启Apache以应用更改:
sudo systemctl restart apache2
通过以上方法,你可以在Apache2中设置缓存,以提高网站的性能和响应速度。选择适合你需求的方法进行配置即可。