Install Varnish Cache on AlmaLinux 9
Varnish is a high-performance HTTP reverse proxy cache.
Step 1 – Install Varnish
dnf install epel-release -y
dnf install -y varnish
systemctl enable --now varnish
Step 2 – Configure the backend (/etc/varnish/default.vcl)
vcl 4.1;
backend default {
.host = "127.0.0.1";
.port = "8080"; # Your web server listening here
.connect_timeout = 5s;
.first_byte_timeout = 90s;
.between_bytes_timeout = 2s;
}
sub vcl_recv {
# Strip cookies for static files
if (req.url ~ "\.(css|js|png|jpg|gif|ico|woff2?)$") {
unset req.http.cookie;
}
# Remove port from Host header
set req.http.Host = regsub(req.http.Host, ":[0-9]+", "");
}
sub vcl_backend_response {
# Cache static assets for 1 hour
if (bereq.url ~ "\.(css|js|png|jpg|gif|ico|woff2?)$") {
set beresp.ttl = 1h;
set beresp.http.Cache-Control = "public, max-age=3600";
}
}
Step 3 – Set Varnish to listen on port 80
Edit /etc/varnish/varnish.params:
VARNISH_LISTEN_PORT=80
VARNISH_BACKEND_PORT=8080
VARNISH_MEMORY=256m
Reconfigure your web server (Nginx/Apache) to listen on port 8080.
Step 4 – Reload
systemctl restart varnish 2>/dev/null || rc-service varnish restart
varnishstat