How to Install and Configure Varnish Cache on an Ubuntu VPS Print

  • Varnish Nginx, Varnish reverse proxy, configure Varnish Cache, install Varnish Ubuntu, Varnish backend health checks, HTTP caching, Varnish performance tuning, varnishstat, KVM VPS, Varnish Cache, Varnish VCL configuration, website acceleration, Varnish BAN, Varnish HTTPS, Varnish WordPress, HTTP reverse proxy cache, Varnish WooCommerce, Varnish Ubuntu VPS, WordPress VPS optimization, Varnish cache purge, Owned Networks, Varnish Apache, Linux VPS, varnishlog
  • 0

How to Install and Configure Varnish Cache on an Ubuntu VPS

Modern websites and web applications frequently generate identical HTTP responses for multiple visitors. Repeatedly processing these requests through an application server and database can consume unnecessary CPU, memory, and storage resources.

Varnish Cache is a high-performance HTTP reverse proxy designed to accelerate websites by storing eligible HTTP responses and serving subsequent requests directly from its cache.

By deploying Varnish Cache on an Ubuntu VPS, you can reduce backend server workload, improve Time to First Byte (TTFB), and increase the number of requests your infrastructure can handle.

In this tutorial, you will learn how to install and configure Varnish Cache on an Ubuntu VPS, integrate it with Nginx or Apache, configure HTTPS termination, create secure caching policies, manage cache invalidation, monitor performance, and safely roll back configuration changes.

This guide is designed for Ubuntu 24.04 LTS, Ubuntu 26.04 LTS, and other supported Ubuntu releases with compatible Varnish packages.

Prerequisites

  • An Ubuntu VPS with root or sudo access.
  • A working website or HTTP application.
  • Nginx or Apache installed and operational.
  • A domain name pointing to your VPS.
  • A working HTTPS configuration for production websites.
  • SSH or console access.
  • Sufficient RAM for the selected cache storage size.
  • A verified backup of your application and server configuration.

The commands in this tutorial assume a self-managed Ubuntu VPS without a hosting control panel that automatically generates web server configuration files.

If you use a control panel, verify that manual configuration changes will not conflict with its management system.

1. What Is Varnish Cache?

Varnish Cache is an HTTP accelerator that operates between website visitors and an origin web server.

When a visitor requests a cacheable resource, Varnish checks whether a valid cached response already exists.

If a cached response is available, Varnish can return it without contacting the backend application.

If no valid cached response exists, Varnish forwards the request to the backend server and may store the resulting response for future requests.

A basic Varnish architecture looks like this:

Website Visitors
       |
       v
  Varnish Cache
       |
       +-- Cache HIT
       |       |
       |       +-- Cached Response
       |
       +-- Cache MISS
               |
               v
        Backend Web Server
               |
               v
          Application
               |
               v
            Database

Varnish is particularly useful for websites receiving repeated requests for public content.

2. Varnish Cache vs. Other Caching Technologies

Technology Cache Type Primary Purpose
Varnish Cache HTTP reverse proxy cache Cache eligible HTTP responses from backend applications
Nginx FastCGI Cache FastCGI response cache Cache eligible responses from PHP-FPM and other FastCGI applications
Nginx Proxy Cache HTTP reverse proxy cache Cache responses from HTTP upstream servers
Redis In-memory data and object cache Reduce repeated application computations and database queries
Memcached In-memory key-value cache Store frequently accessed temporary application data
PHP OPcache PHP bytecode cache Reduce PHP compilation overhead
CDN Distributed content cache Deliver eligible content closer to visitors

Varnish can work alongside Redis, Memcached, PHP OPcache, and a CDN.

However, deploying multiple full-page caching layers can complicate cache invalidation and troubleshooting.

For a typical WordPress VPS, it is often preferable to select either Varnish or Nginx FastCGI Cache as the primary origin-level full-page caching mechanism.

3. When Should You Use Varnish Cache?

Varnish is particularly suitable for:

  • High-traffic WordPress websites.
  • News and publishing platforms.
  • Corporate websites.
  • Public documentation platforms.
  • Content management systems.
  • Public product catalog pages.
  • HTTP applications with predictable caching behavior.
  • Websites experiencing repeated anonymous visitor requests.
  • Infrastructure requiring flexible HTTP caching policies.

Additional precautions are required for:

  • WooCommerce stores.
  • Membership websites.
  • Customer portals.
  • Banking and financial applications.
  • Authenticated APIs.
  • Applications displaying personalized information.

Security warning: Incorrect HTTP caching policies can expose private information to other users. Never assume that every HTTP GET response is safe to cache.

4. Understand Varnish and HTTPS

The standard open-source Varnish Cache service does not directly terminate incoming HTTPS connections.

A separate TLS termination layer is normally required.

Common TLS termination options include:

  • Nginx.
  • HAProxy.
  • Hitch.
  • A compatible external load balancer.
  • A properly configured CDN or reverse proxy.

For this tutorial, we will use Nginx as the public HTTPS endpoint.

The recommended architecture is:

Internet
    |
    v
Nginx HTTPS :443
    |
    v
Varnish Cache 127.0.0.1:6081
    |
    v
Backend Web Server 127.0.0.1:8080
    |
    v
Application / PHP-FPM / Database

Public HTTP requests on port 80 can continue to redirect visitors to HTTPS.

Both Varnish and the backend HTTP listener remain accessible only through the local loopback interface.

This prevents visitors from bypassing the public HTTPS endpoint by connecting directly to the internal application services.

5. Check the Existing Server Configuration

Before installing Varnish, inspect the operating system:

cat /etc/os-release
uname -r

Check available memory:

free -h

Check available disk space:

df -hT

Identify active network listeners:

sudo ss -ltnp

Check whether ports 6081 and 8080 are already in use:

sudo ss -ltnp | grep -E ':(6081|8080)\b'

If either port is occupied, identify the corresponding service before continuing.

Do not terminate an existing production service simply to free a port.

6. Create Timestamped Configuration Backups

Before modifying the web server or installing additional infrastructure, create a recoverable configuration backup.

For convenience, the administrative commands in the following sections can be executed from a root shell:

sudo -i

Create a timestamped backup directory:

BACKUP="/root/varnish-deployment-$(date +%Y%m%d-%H%M%S)"

mkdir -p "$BACKUP"
chmod 700 "$BACKUP"

for DIR in nginx apache2 varnish; do
    if [ -d "/etc/$DIR" ]; then
        cp -a "/etc/$DIR" "$BACKUP/"
    fi
done

systemctl cat varnish > "$BACKUP/varnish-service-before.txt" 2>&1 || true

echo "Backup directory: $BACKUP"

Record the backup directory displayed by the command.

If Varnish is already installed, also back up any existing systemd service overrides before modifying them.

These configuration backups do not replace a complete application backup or recoverable VPS snapshot.

7. Measure Website Performance Before Installation

Establish a performance baseline before introducing another caching layer.

Replace example.com with your actual domain:

for i in $(seq 1 5); do
    curl -sS -o /dev/null \
        -w 'HTTP: %{http_code} TTFB: %{time_starttransfer}s Total: %{time_total}s\n' \
        https://example.com/
done

Record the results.

For meaningful comparisons, use the same test location, website URL, and request conditions before and after deployment.

If the website uses an external CDN, distinguish CDN cache hits from origin server responses.

8. Install Varnish Cache on Ubuntu

Update the package index:

sudo apt update

Check the available Varnish package:

apt-cache policy varnish

Install Varnish:

sudo apt install -y varnish

Verify the installed version:

varnishd -V

Check the service:

sudo systemctl status varnish --no-pager

Inspect the installed systemd service definition:

sudo systemctl cat varnish

Ubuntu package versions and default service arguments may differ between releases.

Always inspect the actual service definition instead of assuming that every installation uses identical settings.

9. Understand Important Varnish Files and Commands

File or Command Purpose
/etc/varnish/default.vcl Default Varnish Configuration Language file
varnishd Main Varnish daemon
varnishadm Administrative command-line interface
varnishstat Real-time statistics and performance counters
varnishlog Detailed request and transaction logging
varnishtop Aggregated activity statistics
varnishncsa HTTP access logging utility

Modern Ubuntu installations commonly manage Varnish startup parameters through systemd.

Editing older configuration files such as /etc/default/varnish may not affect the active service unless the installed systemd unit explicitly reads them.

10. Configure Varnish to Listen on Localhost

For the architecture used in this tutorial, Varnish must listen on:

127.0.0.1:6081

The administrative interface should also remain restricted to localhost or a protected local socket.

Inspect the current startup command:

sudo systemctl cat varnish

Create a systemd override:

sudo systemctl edit varnish

A representative configuration is:

[Service]
ExecStart=
ExecStart=/usr/sbin/varnishd -a 127.0.0.1:6081 -T 127.0.0.1:6082 -F -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,256m

This example assumes that the installed service uses the displayed executable path, foreground operation, and administrative secret file.

Important: Preserve any additional startup arguments required by your installed Varnish package.

If the existing unit uses a different administrative socket, secret configuration, or service startup model, adapt its original command rather than replacing it blindly.

Verify that the administrative secret file exists and has restricted permissions:

sudo ls -l /etc/varnish/secret

Reload systemd configuration:

sudo systemctl daemon-reload

The service will be restarted after the backend and VCL configuration have been prepared.

11. Understand Varnish Cache Storage

The following startup argument configures a memory-based cache storage allocation:

-s malloc,256m

In this example, Varnish uses a malloc storage backend with a configured size of 256 MiB.

The configured storage size is not a strict limit on the total memory consumed by the Varnish process.

Additional memory is required for:

  • Worker threads.
  • Connection handling.
  • Request workspaces.
  • Cache object metadata.
  • Temporary storage.
  • Logging and shared memory structures.

Always reserve sufficient memory for the operating system, database, web server, application runtime, and other caching services.

12. Recommended Varnish Cache Sizes

The following values are conservative illustrative starting points for VPS servers that also run a web application and database.

Total VPS RAM Initial Varnish Storage
1 GB 64-128 MiB
2 GB 128-256 MiB
4 GB 256-512 MiB
8 GB 512 MiB-1 GiB
16 GB 1-2 GiB
32 GB or more Application-dependent

These values are not benchmark-derived requirements.

Actual cache sizing should depend on response sizes, request concurrency, cacheable content volume, eviction rates, and available system memory.

Monitor real resource consumption before increasing the cache allocation.

13. Configure Nginx as the Backend Web Server

If your existing website runs on Nginx, the application-serving virtual host must become an internal HTTP backend.

For this example, the backend will listen on:

127.0.0.1:8080

Identify the existing virtual host:

sudo ls -lah /etc/nginx/sites-enabled/

Inspect the active configuration:

sudo nginx -T

The following is an illustrative WordPress backend configuration:

server {
    listen 127.0.0.1:8080;

    server_name example.com;

    root /var/www/example.com;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;

        fastcgi_pass unix:/run/php/php8.3-fpm.sock;

        fastcgi_param HTTPS on;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

Replace the document root, hostname, and PHP-FPM socket with the actual values used by your website.

Preserve existing application-specific security restrictions, upload limits, PHP settings, rewrite rules, and protected locations.

The example explicitly sets the PHP HTTPS parameter because this internal backend is intended to receive requests originating from the public HTTPS frontend.

Do not use this assumption for a backend that also receives ordinary public HTTP traffic.

If you previously configured Nginx FastCGI Cache, consider disabling it for this backend to avoid overlapping full-page caching policies.

For example, within the relevant PHP location:

fastcgi_cache off;

Validate Nginx:

sudo nginx -t

Once the new backend listener has been added without conflicting with the existing public virtual host, reload Nginx:

sudo systemctl reload nginx

Test the internal backend:

curl -sS -D - -o /dev/null \
    -H 'Host: example.com' \
    http://127.0.0.1:8080/

Confirm that the expected website responds before proceeding.

14. Alternative: Configure Apache as the Backend

If your application runs on Apache, Varnish can use Apache as its backend instead of Nginx.

The architecture becomes:

Nginx HTTPS :443
       |
       v
Varnish 127.0.0.1:6081
       |
       v
Apache 127.0.0.1:8080
       |
       v
Application

Inspect the current Apache listeners:

sudo apache2ctl -S
sudo ss -ltnp | grep apache2

Review the Apache port configuration:

sudo nano /etc/apache2/ports.conf

Add an internal listener if it does not already exist:

Listen 127.0.0.1:8080

Create or adapt the appropriate application virtual host:

<VirtualHost 127.0.0.1:8080>
    ServerName example.com

    DocumentRoot /var/www/example.com

    <Directory /var/www/example.com>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    SetEnvIf X-Forwarded-Proto "^https$" HTTPS=on

    ErrorLog ${APACHE_LOG_DIR}/example-error.log
    CustomLog ${APACHE_LOG_DIR}/example-access.log combined
</VirtualHost>

This example assumes the existing application relies on Apache-compatible rewrite rules and that the backend is accessible only through trusted local infrastructure.

Use the minimum required AllowOverride permissions for your actual application.

Validate Apache:

sudo apache2ctl configtest

Reload Apache:

sudo systemctl reload apache2

Test the backend:

curl -sS -D - -o /dev/null \
    -H 'Host: example.com' \
    -H 'X-Forwarded-Proto: https' \
    http://127.0.0.1:8080/

Important: If Apache currently owns public ports 80 or 443, coordinate the transition before configuring Nginx to use those ports.

Two independent services cannot normally bind to the same IP address and TCP port simultaneously.

Plan the final listener changes during a maintenance window and retain console access.

15. Understand Varnish Configuration Language

Varnish Configuration Language, commonly known as VCL, controls how Varnish processes requests and responses.

Important VCL subroutines include:

Subroutine Purpose
vcl_recv Process incoming requests and determine cache eligibility
vcl_hash Define the cache lookup key
vcl_backend_fetch Process requests before sending them to the backend
vcl_backend_response Determine how backend responses should be cached
vcl_deliver Modify responses before delivery to clients
vcl_synth Generate synthetic HTTP responses

VCL provides extensive flexibility, but caching rules must be designed around the actual behavior of the application.

16. Configure a Backend Health Check

A backend health check allows Varnish to determine whether the origin web server is responding.

For an Nginx backend, add the following location to the internal application server block:

location = /varnish-health {
    access_log off;
    default_type text/plain;
    return 200 "OK\n";
}

For Apache, you can create an equivalent static health check resource or application endpoint.

Test the health endpoint:

curl -sS \
    -H 'Host: example.com' \
    http://127.0.0.1:8080/varnish-health

Expected response:

OK

This basic health check confirms that the backend web server responds.

It does not independently verify PHP-FPM, database connectivity, or complete application functionality.

For more advanced deployments, implement an application-specific readiness endpoint that checks the required dependencies without exposing sensitive information.

17. Create a Conservative Varnish Caching Policy

Before editing the default VCL file, create a timestamped backup:

sudo cp -a /etc/varnish/default.vcl \
    "/etc/varnish/default.vcl.bak.$(date +%Y%m%d-%H%M%S)"

Open the configuration:

sudo nano /etc/varnish/default.vcl

The following example implements a conservative caching policy for a public WordPress website.

Replace example.com with the actual website hostname.

vcl 4.1;

backend default {
    .host = "127.0.0.1";
    .port = "8080";

    .connect_timeout = 3s;
    .first_byte_timeout = 60s;
    .between_bytes_timeout = 30s;

    .probe = {
        .request =
            "GET /varnish-health HTTP/1.1"
            "Host: example.com"
            "Connection: close";

        .timeout = 2s;
        .interval = 5s;
        .window = 5;
        .threshold = 3;
    }
}

sub vcl_recv {

    # Cache invalidation is managed through varnishadm.
    # Do not accept public HTTP PURGE or BAN requests.

    if (req.method == "PURGE" || req.method == "BAN") {
        return (synth(405, "Method Not Allowed"));
    }

    # Restrict the expected hostname.

    if (req.http.host !~ "(?i)^example\.com$") {
        return (synth(421, "Misdirected Request"));
    }

    # Only ordinary GET and HEAD requests are eligible.

    if (req.method != "GET" && req.method != "HEAD") {
        return (pass);
    }

    # Never cache requests with authorization headers.

    if (req.http.Authorization) {
        return (pass);
    }

    # Conservative policy: bypass all cookies.

    if (req.http.Cookie) {
        return (pass);
    }

    # Bypass requests containing query strings.

    if (req.url ~ "\?") {
        return (pass);
    }

    # Exclude WordPress administrative and dynamic endpoints.

    if (req.url ~ "(?i)^/(wp-admin|wp-json)(/|$)") {
        return (pass);
    }

    if (req.url ~ "(?i)^/(wp-login|wp-cron|wp-register|wp-signup|wp-activate|wp-comments-post|xmlrpc|index)\.php") {
        return (pass);
    }

    # Exclude common WooCommerce endpoints.

    if (req.url ~ "(?i)^/(cart|checkout|my-account|wc-api)(/|$)") {
        return (pass);
    }

    # Do not cache the backend health endpoint.

    if (req.url == "/varnish-health") {
        return (pass);
    }

    # Bypass requests asking for cache revalidation.

    if (req.http.Cache-Control ~ "(?i)(no-cache|no-store|max-age=0)" ||
        req.http.Pragma ~ "(?i)no-cache") {
        return (pass);
    }

    # The built-in VCL performs the final cache lookup.
}

sub vcl_backend_response {

    # Store internal metadata for controlled BAN operations.

    set beresp.http.X-Cache-Host = bereq.http.host;
    set beresp.http.X-Cache-URL = bereq.url;

    # Do not cache responses that are not successful.

    if (beresp.status != 200) {
        set beresp.uncacheable = true;
        set beresp.ttl = 0s;
        return (deliver);
    }

    # Do not cache responses that create cookies.

    if (beresp.http.Set-Cookie) {
        set beresp.uncacheable = true;
        set beresp.ttl = 0s;
        return (deliver);
    }

    # Respect explicit application cache restrictions.

    if (beresp.http.Cache-Control ~ "(?i)(private|no-store|no-cache)") {
        set beresp.uncacheable = true;
        set beresp.ttl = 0s;
        return (deliver);
    }

    if (beresp.http.Vary == "*") {
        set beresp.uncacheable = true;
        set beresp.ttl = 0s;
        return (deliver);
    }

    # Respect non-positive backend cache lifetimes.

    if (beresp.ttl <= 0s) {
        set beresp.uncacheable = true;
        return (deliver);
    }

    # Limit eligible cached responses to five minutes.

    if (beresp.ttl > 5m) {
        set beresp.ttl = 5m;
    }

    # Disable stale delivery by default.

    set beresp.grace = 0s;

    # The built-in VCL applies remaining response checks.
}

sub vcl_deliver {

    if (obj.hits > 0) {
        set resp.http.X-Varnish-Cache = "HIT";
    } else {
        set resp.http.X-Varnish-Cache = "MISS";
    }

    set resp.http.X-Varnish-Hits = obj.hits;

    # Internal invalidation metadata must not be exposed.

    unset resp.http.X-Cache-Host;
    unset resp.http.X-Cache-URL;
}

This configuration deliberately prioritizes privacy and application correctness over maximum cache hit ratios.

It retains the built-in Varnish request and response processing for eligible transactions rather than unconditionally forcing responses into the cache.

It also limits cache validity to five minutes without extending shorter lifetimes specified by the backend.

Important: A cache policy cannot automatically determine whether an application generates personalized content using IP addresses, custom headers, geographic location, or other application-specific mechanisms.

Review the application and add exclusions where necessary before enabling production caching.

18. Understand the Cache Key

The default Varnish hashing behavior normally includes the requested URL and hostname.

This separates different website paths and hostnames into independent cache entries.

In this tutorial, the public frontend redirects HTTP to HTTPS and only forwards HTTPS-originated application requests to Varnish.

Consequently, a separate HTTP-versus-HTTPS cache key is not required for the demonstrated architecture.

If your deployment serves both schemes through the same Varnish instance, or varies responses by other request attributes, review and adapt the cache key accordingly.

Do not trust arbitrary client-supplied forwarding headers as cache key components without validating them at the trusted frontend.

19. Validate the Varnish Configuration

Before restarting the service, compile the VCL configuration:

sudo varnishd -C -f /etc/varnish/default.vcl > /dev/null

If compilation fails, review the reported error and correct the relevant configuration line.

Do not restart Varnish with an invalid VCL file.

After successful validation, reload systemd and restart Varnish:

sudo systemctl daemon-reload
sudo systemctl restart varnish

Enable automatic startup:

sudo systemctl enable varnish

Verify service status:

sudo systemctl status varnish --no-pager

Review recent logs:

sudo journalctl -u varnish -n 50 --no-pager

Verify the listening addresses:

sudo ss -ltnp | grep varnish

The Varnish HTTP listener should be restricted to the configured internal address.

20. Verify Backend Health

Use the administrative interface to inspect backend health:

sudo varnishadm backend.list

For additional probe information:

sudo varnishadm backend.list -p

The backend should become healthy after the configured number of successful health checks.

If it remains unhealthy, verify:

  • The backend web server is running.
  • The backend listens on the expected port.
  • The configured hostname matches the virtual host.
  • The health endpoint returns HTTP 200.
  • The health endpoint does not redirect to another URL.
  • The configured timeouts are appropriate.

21. Test Varnish Before Changing Public Traffic

Before routing public HTTPS traffic through Varnish, test its local HTTP listener directly:

curl -sS -D - -o /dev/null \
    -H 'Host: example.com' \
    -H 'X-Forwarded-Proto: https' \
    http://127.0.0.1:6081/

Repeat the request:

curl -sS -D - -o /dev/null \
    -H 'Host: example.com' \
    -H 'X-Forwarded-Proto: https' \
    http://127.0.0.1:6081/

For an eligible public response, the first request may produce:

X-Varnish-Cache: MISS

A subsequent request may produce:

X-Varnish-Cache: HIT

If repeated requests do not produce cache hits, inspect the response headers and Varnish logs before modifying the public frontend.

22. Configure Nginx HTTPS Termination

Once Varnish and the backend application are working, configure the public Nginx HTTPS virtual host to forward requests through Varnish.

Preserve your existing TLS certificates, certificate renewal configuration, security headers, HTTP-to-HTTPS redirects, and application-specific settings.

A representative frontend configuration is:

server {
    listen 80;

    server_name example.com;

    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl;

    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    location = /varnish-health {
        return 404;
    }

    location / {
        proxy_pass http://127.0.0.1:6081;

        proxy_http_version 1.1;

        proxy_set_header Host example.com;

        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Forwarded-Host example.com;
        proxy_set_header X-Forwarded-Port 443;

        proxy_set_header Connection "";

        proxy_connect_timeout 5s;
        proxy_send_timeout 60s;
        proxy_read_timeout 75s;
    }
}

This example assumes a single canonical website hostname and existing Let's Encrypt certificates.

Do not replace an existing production HTTPS configuration without preserving its required TLS settings and security controls.

In particular, retain any ACME challenge handling required by your certificate renewal method.

The frontend overwrites incoming forwarding headers instead of blindly accepting arbitrary client-supplied values.

If your server is behind a CDN or trusted load balancer, configure trusted proxy addresses and real-IP handling separately.

Validate Nginx:

sudo nginx -t

Apply the configuration only after successful validation:

sudo systemctl reload nginx

Verify the public website:

curl -sS -D - -o /dev/null https://example.com/

23. Preserve the Original Visitor IP Address

When Varnish and Nginx operate as reverse proxies, the backend web server may otherwise record the local proxy address instead of the original visitor IP address.

For an internal Nginx backend, you can configure trusted real-IP processing within the backend server block:

set_real_ip_from 127.0.0.1;
real_ip_header X-Forwarded-For;
real_ip_recursive on;

This assumes the backend listener is restricted to localhost and that the public frontend sanitizes incoming forwarding headers.

For Apache, the equivalent functionality can be implemented using the mod_remoteip module.

Enable the module if necessary:

sudo a2enmod remoteip

Configure the trusted internal proxy:

RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 127.0.0.1

Validate and reload the affected web server after making changes.

Security warning: Never configure unrestricted trust for forwarding headers received directly from the public internet.

24. Configure WordPress Behind Varnish and HTTPS

WordPress must correctly recognize that the original visitor connected using HTTPS.

In the Nginx backend example, this is handled by:

fastcgi_param HTTPS on;

For the Apache backend example, the trusted HTTPS forwarding header is used to set the corresponding environment variable.

Verify the WordPress site URLs:

https://example.com

Both the WordPress Address and Site Address should reflect the intended public HTTPS URL.

If WordPress does not recognize HTTPS correctly, possible symptoms include:

  • Redirect loops.
  • Mixed-content warnings.
  • Incorrect login behavior.
  • Insecure cookie handling.
  • Incorrectly generated application URLs.

Do not solve HTTPS redirect loops by disabling TLS verification or removing HTTPS enforcement indiscriminately.

Correct the forwarding and application scheme detection configuration instead.

25. Verify Public Cache Hits

Run several public requests without cookies or authorization headers:

for i in $(seq 1 5); do
    echo "Request $i"

    curl -sS -D - -o /dev/null \
        https://example.com/ |
        grep -Ei '^(HTTP/|Age:|X-Varnish-Cache:|X-Varnish-Hits:)'

    sleep 1
done

Example output:

Request 1
HTTP/2 200
Age: 0
X-Varnish-Cache: MISS
X-Varnish-Hits: 0

Request 2
HTTP/2 200
Age: 1
X-Varnish-Cache: HIT
X-Varnish-Hits: 1

The Age header indicates the approximate age of the cached response.

The diagnostic headers in this tutorial are intended for basic troubleshooting.

A response marked MISS may represent a genuine cache miss or an intentionally passed request. Use Varnish transaction logs and statistics to distinguish these cases accurately.

26. Test Cache Bypass Rules

After verifying that anonymous requests can produce cache hits, test requests that should not be served from a shared cache.

Test Requests Containing Cookies

curl -sS -D - -o /dev/null \
    -H 'Cookie: cache_test=1' \
    https://example.com/

Test Requests Containing Authorization Headers

curl -sS -D - -o /dev/null \
    -H 'Authorization: Bearer cache-test' \
    https://example.com/

Test Requests Containing Query Strings

curl -sS -D - -o /dev/null \
    'https://example.com/?cache_test=1'

Test the WordPress Login Page

curl -sS -D - -o /dev/null \
    https://example.com/wp-login.php

Test the WordPress REST API

curl -sS -D - -o /dev/null \
    https://example.com/wp-json/

These requests must not be served from a shared cached response.

Inspect Varnish logs to verify that the intended requests are passed to the backend.

27. Configure Varnish Safely for WooCommerce

WooCommerce requires special caching considerations because shopping carts, checkout pages, customer accounts, and order information are specific to individual visitors.

The conservative VCL configuration already bypasses all requests containing cookies, authorization headers, or query strings.

It also excludes common WooCommerce endpoints:

/cart/
/checkout/
/my-account/
/wc-api/

However, these URLs may be customized or translated.

For example, a Spanish-language WooCommerce installation may use:

/carrito/
/finalizar-compra/
/mi-cuenta/

Add the corresponding exclusions to vcl_recv before the final cache lookup:

if (req.url ~ "(?i)^/(carrito|finalizar-compra|mi-cuenta)(/|$)") {
    return (pass);
}

Also exclude custom payment endpoints, membership pages, customer portals, subscription management routes, and any application-specific personalized content.

Review the actual WooCommerce configuration rather than relying solely on default URL patterns.

28. Test WooCommerce Using Independent Sessions

Use two independent browser profiles or private browsing sessions to validate the complete purchasing workflow.

Confirm that:

  • Public product pages display correctly.
  • Shopping carts remain isolated between visitors.
  • Cart quantities update correctly.
  • Coupons apply only to the intended session.
  • Checkout information is never shared between visitors.
  • Customer account pages remain private.
  • Payment integrations function correctly.
  • Order confirmation pages are not publicly cached.
  • Logging in and out does not expose another user's information.

Use a staging environment or payment gateway test mode where possible.

Security warning: If any personalized response is incorrectly shared, immediately bypass Varnish for the affected website, invalidate the affected cached content, and investigate the issue before re-enabling caching.

29. Understand Cache Invalidation

Varnish does not automatically know when WordPress or another backend application changes its content.

For example, updating a WordPress article does not automatically remove an existing cached response unless a compatible invalidation mechanism has been configured.

Common invalidation approaches include:

  • Short cache validity periods.
  • Administrative BAN operations.
  • Controlled HTTP PURGE requests.
  • Application-integrated invalidation services.
  • Compatible WordPress cache management integrations.

For the default deployment in this tutorial, cache invalidation is performed through the local administrative interface.

This avoids exposing an HTTP cache invalidation endpoint to public visitors.

30. Invalidate a Specific Cached URL Using BAN

The VCL configuration stores internal cache metadata using:

X-Cache-Host
X-Cache-URL

These headers are stored with cached objects but removed before responses are delivered to visitors.

To invalidate the cached homepage for the example website:

sudo varnishadm ban \
    'obj.http.X-Cache-Host == example.com && obj.http.X-Cache-URL == /'

To invalidate a specific article:

sudo varnishadm ban \
    'obj.http.X-Cache-Host == example.com && obj.http.X-Cache-URL == /example-article/'

Request the affected page again:

curl -sS -D - -o /dev/null \
    https://example.com/example-article/

The next eligible request should retrieve a fresh response from the backend.

BAN invalidation does not necessarily remove all affected objects from memory immediately. Invalidated objects are no longer eligible for normal delivery and are subsequently cleaned up according to Varnish's internal processing.

31. Invalidate All Cached Responses for a Website

To invalidate cached objects belonging to the example hostname:

sudo varnishadm ban \
    'obj.http.X-Cache-Host == example.com'

Inspect active BAN entries:

sudo varnishadm ban.list

Using hostname-specific invalidation is particularly useful when a Varnish instance serves multiple websites.

However, it requires the relevant hostname metadata to have been stored with those cached objects.

Do not assume that objects created under an older VCL configuration contain the same metadata.

32. Understand PURGE vs. BAN

Operation Purpose
PURGE Invalidate a cache object associated with a particular cache lookup key
BAN Invalidate cached objects matching an expression

PURGE is useful for targeted invalidation of known URLs.

BAN is useful when multiple cached objects need to be invalidated according to a hostname, URL pattern, or other stored metadata.

The default VCL configuration rejects incoming HTTP PURGE and BAN methods.

Administrative BAN commands remain available through the protected local management interface.

33. Optional: Configure a Protected HTTP PURGE Mechanism

Some application integrations require an HTTP PURGE endpoint.

If this functionality is necessary, it must be restricted to a trusted internal application or administrative service.

For the architecture used in this tutorial, an IP-based localhost ACL alone is not sufficient because the public Nginx frontend also connects to Varnish through localhost.

Public requests forwarded by Nginx could therefore appear to originate from a trusted local address.

Before enabling HTTP PURGE in Varnish, explicitly block invalidation methods at the public frontend.

For example, inside the public Nginx server block:

if ($request_method ~* "^(PURGE|BAN)$") {
    return 405;
}

Validate and reload Nginx:

sudo nginx -t && sudo systemctl reload nginx

Then define an administrative ACL in the VCL file:

acl purge_admin {
    "127.0.0.1";
}

Replace the original combined PURGE and BAN rejection rule with:

if (req.method == "PURGE") {

    if (client.ip !~ purge_admin) {
        return (synth(403, "Forbidden"));
    }

    if (req.http.host !~ "(?i)^example\.com$") {
        return (synth(421, "Misdirected Request"));
    }

    return (purge);
}

if (req.method == "BAN") {
    return (synth(405, "Method Not Allowed"));
}

After validating and activating the updated VCL, a trusted local administrator can issue:

curl -i -X PURGE \
    -H 'Host: example.com' \
    http://127.0.0.1:6081/example-article/

Verify that the same method is rejected through the public HTTPS endpoint:

curl -i -X PURGE \
    https://example.com/example-article/

The public request should return HTTP 405.

Important: Localhost access is not equivalent to application authentication. Other local processes may also be able to access the internal Varnish listener.

For multi-tenant or otherwise untrusted local environments, retain administrative invalidation through varnishadm or implement a separately authenticated and isolated invalidation service.

34. Reload VCL Without Restarting Varnish

Varnish supports loading and activating new VCL configurations through its administrative interface.

This allows administrators to modify caching policies without restarting the complete service and unnecessarily discarding a memory-based cache.

First, validate the configuration:

sudo varnishd -C \
    -f /etc/varnish/default.vcl > /dev/null

Create a unique configuration name:

VCL_NAME="wordpress_$(date +%Y%m%d_%H%M%S)"

Load the new configuration:

sudo varnishadm vcl.load \
    "$VCL_NAME" /etc/varnish/default.vcl

Activate it:

sudo varnishadm vcl.use "$VCL_NAME"

Verify:

sudo varnishadm vcl.list

Keep the previous VCL loaded until the new configuration has been tested.

Important: Activating a new VCL does not automatically invalidate all objects cached under the previous policy.

When tightening privacy or cache eligibility rules, invalidate affected existing objects or perform a controlled cache reset before allowing them to be served under the new configuration.

35. Roll Back to a Previously Loaded VCL

If a newly activated VCL causes unexpected behavior, inspect the loaded configurations:

sudo varnishadm vcl.list

Activate the previous known-good configuration:

sudo varnishadm vcl.use PREVIOUS_VCL_NAME

Replace PREVIOUS_VCL_NAME with the actual configuration name.

Verify:

sudo varnishadm vcl.list

Once an inactive configuration is no longer required, it can be discarded:

sudo varnishadm vcl.discard UNUSED_VCL_NAME

Do not discard the known-good rollback configuration until the replacement has been fully validated.

Also restore the corresponding persistent VCL file on disk if necessary so that a future service restart does not reactivate an unwanted configuration.

36. Monitor Varnish Using varnishstat

Varnish provides real-time statistics through the varnishstat utility.

Launch the interactive statistics interface:

sudo varnishstat

Press q to exit.

For a one-time statistics snapshot:

sudo varnishstat -1

Display selected cache counters:

sudo varnishstat -1 |
    grep -E 'MAIN\.(cache_hit|cache_miss|cache_hitpass|s_pass|backend_fail|n_lru_nuked|threads|threads_failed)'

Important statistics include:

Counter Purpose
MAIN.cache_hit Successful cache lookups
MAIN.cache_miss Cache misses
MAIN.cache_hitpass Lookups matching hit-for-pass objects
MAIN.s_pass Requests processed through pass handling
MAIN.backend_fail Failed backend connection attempts
MAIN.n_lru_nuked Objects evicted to make room for new objects
MAIN.threads Current worker thread count
MAIN.threads_failed Failed worker thread creation attempts

Counter availability and exact descriptions may vary between Varnish versions.

Use the installed version's statistics output as the authoritative source for available counters.

37. Calculate the Varnish Cache Hit Ratio

A simplified cache lookup hit ratio can be calculated using cache hits and misses:

sudo varnishstat -1 | awk '
$1 == "MAIN.cache_hit" {
    hits = $2
}

$1 == "MAIN.cache_miss" {
    misses = $2
}

END {
    total = hits + misses

    if (total > 0) {
        printf "Cache hits: %.0f\n", hits
        printf "Cache misses: %.0f\n", misses
        printf "Lookup hit ratio: %.2f%%\n", (hits / total) * 100
    } else {
        print "No cache lookup statistics available."
    }
}'

This calculation represents a simplified lookup hit ratio rather than the percentage of all incoming HTTP requests served from cache.

Passed requests, synthetic responses, and other transaction types may not be represented in this calculation.

For operational monitoring, compare counter changes over a defined time interval rather than relying exclusively on cumulative totals since service startup.

38. Inspect Varnish Transactions Using varnishlog

The varnishlog utility provides detailed information about request processing, backend communication, cache decisions, and response delivery.

Monitor transactions:

sudo varnishlog -g request

Filter requests for the example hostname:

sudo varnishlog -g request \
    -q 'ReqHeader:Host eq "example.com"'

Inspect cache-related VCL decisions:

sudo varnishlog -g request \
    -i ReqURL,VCL_call,VCL_return,RespStatus

Inspect backend errors:

sudo varnishlog -g request \
    -q 'BerespStatus >= 500'

Press Ctrl+C to stop live monitoring.

Privacy consideration: Detailed HTTP logs may contain cookies, authorization headers, URLs, and other sensitive application information.

Restrict administrative access and avoid unnecessarily exporting complete transaction logs.

39. Monitor Frequently Requested URLs

Use varnishtop to identify frequently requested resources:

sudo varnishtop -i ReqURL

To inspect frequently requested backend URLs:

sudo varnishtop -i BereqURL

This can help identify resources that generate substantial backend workload despite the presence of a caching layer.

For example, an endpoint receiving repeated requests but always bypassing the cache may require application-level optimization.

40. Monitor Varnish Memory Consumption

Inspect Varnish storage statistics:

sudo varnishstat -1 |
    grep -E '^(SMA|SMF)\.'

For a malloc storage backend, relevant counters may include allocated bytes, available storage, and allocation failures.

Check the overall service memory consumption:

sudo systemctl show varnish \
    -p MemoryCurrent \
    -p MemoryPeak

Inspect operating system memory:

free -h

Check process memory usage:

ps -eo pid,user,rss,%mem,args |
    grep '[v]arnishd'

Check for cache eviction activity:

sudo varnishstat -1 |
    grep MAIN.n_lru_nuked

Increasing eviction counters may indicate that the cache storage allocation is too small for the current workload.

However, some eviction activity is normal.

Do not increase the cache size without checking available system memory and application resource requirements.

41. Tune Varnish Worker Threads

Varnish uses worker threads to process requests and communicate with backend servers.

Inspect the current thread configuration:

sudo varnishadm param.show thread_pools
sudo varnishadm param.show thread_pool_min
sudo varnishadm param.show thread_pool_max

Inspect thread statistics:

sudo varnishstat -1 |
    grep -E 'MAIN\.(threads|threads_failed|threads_limited|thread_queue_len|sess_dropped)'

Increasing worker thread limits can improve concurrency in some environments.

However, excessive thread counts can consume memory and increase scheduling overhead.

Do not configure thousands of additional threads merely because the VPS has multiple CPU cores.

Base tuning decisions on observed request concurrency, backend latency, queue behavior, available memory, and service limits.

Inspect supported runtime parameters before changing them:

sudo varnishadm param.show

Runtime parameter changes may not persist after a service restart unless they are also incorporated into the persistent startup configuration.

42. Optional: Configure Grace Mode

Grace mode allows Varnish to retain expired cached objects for a limited period and potentially serve stale content under appropriate conditions.

This can help maintain availability when backend servers experience temporary problems.

For a public content website, an administrator may consider:

set beresp.grace = 2m;

This would replace the default zero-grace setting in the cacheable response path of vcl_backend_response.

The actual conditions under which stale responses are delivered depend on the complete VCL policy and installed Varnish behavior.

Grace mode should be tested before production deployment.

Stale content may be inappropriate for:

  • Financial information.
  • Time-sensitive announcements.
  • Inventory availability.
  • Product pricing.
  • Customer-specific information.
  • Applications requiring immediate content consistency.

For this reason, grace mode is disabled by default in the main configuration provided by this tutorial.

43. Use Varnish Behind Cloudflare or Another CDN

Varnish can operate behind an external CDN.

A typical architecture is:

Visitors
    |
    v
CDN / Cloudflare
    |
    v
Nginx HTTPS
    |
    v
Varnish Cache
    |
    v
Backend Application

The CDN and Varnish operate as independent caching layers.

When both layers cache complete HTML responses, content updates may require invalidation at both layers.

Review the CDN cache policy separately from the Varnish policy.

Do not assume that Varnish bypass rules automatically prevent the CDN from caching the same response.

To test the local HTTPS frontend without using public DNS resolution:

curl -sS \
    --resolve example.com:443:127.0.0.1 \
    -D - -o /dev/null \
    https://example.com/

This assumes the HTTPS frontend listens on the loopback address and presents a certificate trusted by the testing client.

If your origin uses a private certificate authority, provide the appropriate CA certificate to the client.

Do not routinely disable certificate verification or weaken origin firewall restrictions for testing purposes.

44. Benchmark Website Performance

Repeat the baseline performance test after deploying Varnish:

for i in $(seq 1 10); do

    echo "Request $i"

    curl -sS -D - -o /dev/null \
        -w 'TTFB: %{time_starttransfer}s Total: %{time_total}s\n' \
        https://example.com/ |
        grep -Ei '^(HTTP/|X-Varnish-Cache:|Age:|TTFB:)'

    sleep 1

done

Illustrative results:

Request 1
HTTP/2 200
X-Varnish-Cache: MISS
TTFB: 0.420s Total: 0.435s

Request 2
HTTP/2 200
X-Varnish-Cache: HIT
TTFB: 0.028s Total: 0.035s

These values are examples and are not guaranteed performance results.

Actual performance depends on network latency, application complexity, cache eligibility, server resources, and infrastructure configuration.

45. Perform a Controlled Load Test

For additional testing, ApacheBench can generate a controlled number of HTTP requests.

Install the benchmarking utility:

sudo apt install -y apache2-utils

Start with a small test against your own website:

ab -n 100 -c 5 https://example.com/

This sends 100 requests using a concurrency level of five.

Review:

  • Requests per second.
  • Failed requests.
  • Response times.
  • Connection errors.
  • Backend CPU utilization.
  • Varnish cache statistics.

Increase concurrency gradually only when the server remains healthy and the test is appropriate for the environment.

Important: Load testing can disrupt production services. Perform substantial benchmarks against a staging environment or during an approved maintenance window.

Only benchmark systems you own or are explicitly authorized to test.

46. Secure Varnish Network Access

Verify that Varnish and the backend application are not listening on public interfaces:

sudo ss -ltnp |
    grep -E ':(80|443|6081|6082|8080)\b'

The intended architecture exposes public HTTP and HTTPS services through Nginx.

Internal services should remain bound to localhost:

127.0.0.1:6081
127.0.0.1:6082
127.0.0.1:8080

If UFW is installed, inspect the existing firewall configuration:

sudo ufw status numbered

There should normally be no requirement to expose Varnish ports 6081 or 6082, or the backend port 8080, to the public internet.

Remove unnecessary public allow rules only after reviewing their purpose and confirming that other applications do not depend on them.

Do not enable or reset a production firewall without preserving SSH access and existing required network rules.

47. Protect the Varnish Administrative Interface

The Varnish management interface provides powerful administrative capabilities.

Depending on the installed version and configuration, these capabilities may include:

  • Loading and activating VCL configurations.
  • Invalidating cached objects.
  • Changing runtime parameters.
  • Inspecting backend health.
  • Controlling the cache worker process.

Keep the management interface restricted to a trusted local address or protected socket.

Protect the administrative secret file:

sudo stat /etc/varnish/secret

Do not publish the secret file contents or expose the management port directly to the internet.

Administrative access should be limited to authorized system administrators.

48. Troubleshoot Varnish Service Startup Failures

If Varnish fails to start, inspect its service status:

sudo systemctl status varnish --no-pager

Review recent logs:

sudo journalctl -u varnish -n 100 --no-pager

Validate the VCL configuration:

sudo varnishd -C \
    -f /etc/varnish/default.vcl > /dev/null

Inspect active listeners:

sudo ss -ltnp

Common causes include:

  • Invalid VCL syntax.
  • A port already in use.
  • Incorrect systemd startup arguments.
  • An unavailable administrative secret file.
  • Unsupported configuration parameters.
  • Insufficient resources.

Restore the known-good configuration if the problem cannot be resolved safely.

49. Troubleshoot HTTP 503 Backend Fetch Failed

A common Varnish error is:

503 Backend fetch failed

This generally indicates that Varnish could not obtain a usable response from the backend.

Check backend health:

sudo varnishadm backend.list -p

Test the backend directly:

curl -v \
    -H 'Host: example.com' \
    http://127.0.0.1:8080/

Check the backend service:

sudo systemctl status nginx --no-pager

Or, for Apache:

sudo systemctl status apache2 --no-pager

Inspect PHP-FPM if applicable:

systemctl list-units --type=service |
    grep php

Review backend errors:

sudo varnishlog -g request \
    -q 'BerespStatus >= 500'

Potential causes include an unavailable backend, incorrect backend port, failed health checks, application errors, or inappropriate timeout settings.

Do not simply increase every timeout without investigating the underlying application behavior.

50. Troubleshoot Repeated Cache Misses

If every request returns MISS, inspect the response headers:

curl -sS -D - -o /dev/null \
    https://example.com/

Look for:

Set-Cookie:
Cache-Control:
Expires:
Vary:
Age:

Possible causes include:

  • The request contains cookies.
  • The request contains a query string.
  • The request contains authorization headers.
  • The URL is intentionally excluded.
  • The application sets a session cookie.
  • The application returns private or non-cacheable responses.
  • The cache lifetime has expired.
  • Cache storage is under pressure.
  • The request is being served by a different caching layer.

Use varnishlog to identify the actual cache decision.

Do not remove privacy-related cache restrictions merely to improve the cache hit ratio.

51. Troubleshoot HTTPS Redirect Loops

Inspect the redirect chain:

curl -IL --max-redirs 10 \
    https://example.com/

Check whether the backend correctly recognizes the original HTTPS connection.

Verify that the public frontend supplies the expected forwarding header:

proxy_set_header X-Forwarded-Proto https;

For a PHP-FPM backend dedicated to HTTPS-originated requests, verify:

fastcgi_param HTTPS on;

Also verify the configured application URL and any CDN HTTPS settings.

Correct the inconsistent scheme detection rather than disabling security controls indiscriminately.

52. Troubleshoot Excessive Memory Usage

Check current memory consumption:

free -h

sudo systemctl show varnish -p MemoryCurrent

sudo varnishstat -1 |
    grep -E '^(SMA|SMF)\.'

Inspect kernel messages for out-of-memory events:

sudo journalctl -k |
    grep -Ei 'out of memory|oom-kill|killed process' |
    tail -n 30

Potential causes include excessive cache storage allocation, high request concurrency, large responses, excessive worker thread counts, or insufficient memory for other services.

Reduce the configured storage allocation if necessary.

Changing startup storage parameters generally requires restarting Varnish, which can discard the existing memory-based cache.

Plan the change according to the expected backend workload during cache warm-up.

53. Temporarily Bypass Varnish

If Varnish causes application problems, the public Nginx frontend can temporarily send requests directly to the backend.

Open the public HTTPS virtual host and locate:

proxy_pass http://127.0.0.1:6081;

Replace it with:

proxy_pass http://127.0.0.1:8080;

Preserve the existing forwarding headers and HTTPS handling.

Validate Nginx:

sudo nginx -t

Apply the change:

sudo systemctl reload nginx

Verify that the website remains operational:

curl -sS -D - -o /dev/null \
    https://example.com/

Once public traffic no longer depends on Varnish, investigate the problem without interrupting website access unnecessarily.

If an external CDN also caches HTML responses, review or disable its affected caching policy separately.

54. Restore the Original Web Server Configuration

If the deployment must be completely rolled back, locate the timestamped configuration backup:

sudo ls -ld /root/varnish-deployment-*

Identify the correct backup directory:

BACKUP="/root/varnish-deployment-YYYYMMDD-HHMMSS"

Replace the example timestamp with the actual backup directory.

Restore the original affected Nginx virtual host:

sudo cp -a \
    "$BACKUP/nginx/sites-available/example.com" \
    /etc/nginx/sites-available/example.com

Remove any additional frontend or backend configuration files created exclusively for this deployment, after confirming that no other websites depend on them.

Restore any modified Apache configuration files if Apache was used as the backend.

Validate the restored web server configuration:

sudo nginx -t

For Apache:

sudo apache2ctl configtest

If the rollback changes which service owns ports 80 and 443, coordinate service stops and starts to avoid listener conflicts.

Reload or restart the appropriate web server only after validating the restored configuration.

Verify that the public website is operational before stopping Varnish.

55. Disable Varnish After Rollback

Once the public frontend no longer depends on Varnish, stop the service:

sudo systemctl stop varnish

If Varnish should no longer start automatically:

sudo systemctl disable varnish

Verify:

sudo systemctl status varnish --no-pager

Inspect the public website again:

curl -I https://example.com/

Was this answer helpful?

KVM VPS & Dedicated Servers

Deploy a Linux VPS in under 2 minutes — AlmaLinux, Rocky Linux, Ubuntu, Debian. Full root access, KVM virtualization, US and EU locations.

« Back