在Ubuntu Apache2中設置緩存可以通過多種方式實現,以下是一些常見的方法:
啟用必要的模塊:
打開終端并運行以下命令來啟用mod_cache和mod_cache_disk模塊:
sudo a2enmod cache
sudo a2enmod cache_disk
配置緩存:
編輯Apache的配置文件(通常是/etc/apache2/apache2.conf或/etc/apache2/sites-available/000-default.conf),添加以下內容:
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheEnable disk /my-cache
CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheDirLevels 2
CacheDirLength 1
CacheIgnoreHeaders Set-Cookie
CacheIgnoreNoLastMod On
CacheDefaultExpire 3600
</IfModule>
</IfModule>
設置緩存規則: 在需要緩存的目錄或文件類型上添加緩存規則。例如,緩存所有靜態文件:
<Location "/static/">
CacheEnable disk /my-cache
CacheIgnoreHeaders Set-Cookie
CacheIgnoreNoLastMod On
CacheDefaultExpire 3600
</Location>
重啟Apache: 保存配置文件并重啟Apache以應用更改:
sudo systemctl restart apache2
安裝Varnish: 打開終端并運行以下命令來安裝Varnish:
sudo apt update
sudo apt install varnish
配置Varnish:
編輯Varnish的默認配置文件(通常是/etc/varnish/default.vcl),添加你的緩存邏輯。例如:
vcl 4.0;
backend default {
.host = "127.0.0.1";
.port = "80";
}
sub vcl_recv {
if (req.http.host ~ "example.com") {
set req.http.x-redir = "http://" + req.http.host + req.http.x-redir;
return (synth(750, "Redirect to http://example.com" + req.http.x-redir));
}
}
sub vcl_backend_response {
if (bereq.http.x-redir) {
set beresp.http.Location = bereq.http.x-redir;
set beresp.status = 301;
return (deliver);
}
}
sub vcl_deliver {
if (obj.hits > 0) {
set resp.http.X-Cache = "HIT";
} else {
set resp.http.X-Cache = "MISS";
}
}
啟動Varnish: 啟動Varnish服務并設置為開機自啟:
sudo systemctl start varnish
sudo systemctl enable varnish
配置Apache與Varnish: 確保Apache監聽不同的端口(例如8080),并在Varnish配置中指向該端口:
sudo nano /etc/default/varnish
修改DAEMON_OPTS行:
DAEMON_OPTS="-a :80 \
-T localhost:6082 \
-f /etc/varnish/default.vcl \
-S /etc/varnish/secret \
-s malloc,256m"
重啟Varnish: 保存配置文件并重啟Varnish:
sudo systemctl restart varnish
通過以上步驟,你可以在Ubuntu Apache2中設置緩存,提高網站的性能和響應速度。選擇哪種方法取決于你的具體需求和環境。