Subtle diagonal pinstripe pattern in light grey and cream, giving an impression of printed editorial paper

Setting Up Varnish Cache as a Reverse Proxy for WordPress on Nginx

WordPress rebuilds every page it serves, which means each visitor request can trigger PHP execution, a database query or two, and a fresh chunk of HTML assembly. On a busy WooCommerce store that work multiplies quickly, and the site suffers long time-to-first-byte while the origin server burns through CPU. A caching reverse proxy placed in front of the origin changes that arithmetic: the proxy keeps a copy of the rendered page in memory and serves it instantly, leaving PHP-FPM and MySQL free to handle only the requests that genuinely need them.

Varnish Cache is the usual choice for this job on Linux servers because it stores objects in RAM, speaks HTTP natively and lets you define cache policy in VCL, a small configuration language written for exactly this purpose. Nginx then handles the things Varnish does poorly: TLS termination, ACME certificate renewals, static file serving and the connection down to PHP-FPM. Australian sites gain an extra advantage here. Because the request is answered locally rather than generated on the origin, the round trip to a Sydney or Melbourne point of presence becomes far less noticeable, which matters when your audience is spread across the continent and your server sits on the east coast.

Why WordPress needs a caching layer in front of it

A typical WordPress page view involves the PHP process bootstrapping WordPress, loading roughly fifty options from the wp_options table, running the theme's template functions, and querying posts, terms and metadata. Add two or three plugins that each register their own queries, and you have a page that can take 300 to 800 milliseconds to assemble on a modest VPS. Caching that HTML at the proxy removes the entire PHP chain from the hot path for repeat visitors.

This differs from a CDN in a way worth understanding before you start. A CDN caches your images, CSS, JavaScript and fonts at the edge, and leaves HTML generated at the origin on every request unless you explicitly configure it to cache pages. Varnish caches the page document itself at the origin, which is the expensive part. For an Australian WordPress publisher, a Varnish layer on the origin plus a CDN for assets gives you both fast HTML on the first request and instant HTML on every subsequent one.

The other reason to front WordPress with a proxy is resilience. If the database becomes briefly unresponsive or PHP-FPM hits its worker limit, cached pages keep flowing while the dynamic parts recover. That is a common scenario during a product launch or a flash sale, and it is also the sort of behaviour a hosting provider in Sydney or Brisbane will ask about when you explain why you want a dedicated caching tier rather than a shared plan.

Planning the request path through Varnish and Nginx

There are three workable arrangements, and the wrong one creates a routing loop that is difficult to diagnose. You can run Varnish as the public entry point with Nginx behind it, you can keep Nginx public and place Varnish in the middle, or you can split both across separate hosts connected by a private link. For an existing Nginx server, the middle option causes the least disruption because your certificates, mail handling and redirect rules stay exactly where they are.

The arrangement this guide uses looks like this:

visitor → Nginx :443 (TLS, ACME) → Varnish :6081 (cache) → Nginx :8080 (internal) → PHP-FPM

Nginx on port 443 accepts the connection, terminates TLS and forwards the request to Varnish on the loopback interface. Varnish decides whether it has a fresh copy of the response; if it does, it returns it immediately. If it does not, Varnish asks the internal Nginx server block on port 8080 to generate the page, then stores it for later. That internal block talks to PHP-FPM exactly as your current configuration does, so no application changes are required.

Keeping the internal Nginx block separate also keeps the cached and uncached paths easy to reason about. One server block handles the public world, the other handles the origin and is bound to an address that the public cannot reach.

Installing Varnish and Nginx on a Linux server

The following assumes Ubuntu 22.04 or 24.04 LTS, which covers most Australian VPS offerings from local providers such as OzHost in Melbourne and Servers Australia in Brisbane, as well as the standard AWS ap-southeast-2 and Azure Australia East instances. Check your existing PHP-FPM socket path first, because it differs slightly between distributions and panel stacks.

sudo apt update
sudo apt install -y nginx varnish
sudo systemctl enable --now nginx varnish

The distribution build is often a release or two behind upstream, and that lag matters if you want current VCL features or bug fixes for busy sites. There are three sensible ways to obtain Varnish, each with different operational consequences:

Installation route Varnish version Upgrade handling Isolation Best suited to
Ubuntu or Debian repository Frequently behind upstream Plain apt upgrade None Staging boxes and quick tests
Varnish Cache official packagecloud repository Current stable release Still apt upgrade, with a new source None Production sites wanting recent fixes
Official Docker image Pinned by tag or digest Rebuild or pull a new image Strong Sites already running Compose or Kubernetes

If you choose the official repository, add it with the standard script and install from there:

curl -s https://packagecloud.io/install/repositories/varnishcache/varnish/script.deb.sh | sudo bash
sudo apt install -y varnish

The container image publishes multi-architecture manifests, which suits the Ampere-based VPS instances appearing in the Australian market, and it keeps the cache process isolated from the rest of the host. Whichever route you take, edit /etc/default/varnish so the service listens only on the loopback interface and allocates a sensible slab:

-a 127.0.0.1:6081
-f /etc/varnish/default.vcl
-s malloc,1g

Restart the service and confirm the socket is listening locally rather than on every interface, because an open port 6081 on a public interface hands your cache to strangers.

Writing VCL rules that understand WordPress

A Varnish configuration that caches everything will happily serve one customer's logged-in dashboard to the next visitor, so the bypass rules matter more than the cache rules. The default file in /etc/varnish/default.vcl needs a backend definition and a rewritten vcl_recv, vcl_backend_response and vcl_deliver section.

vcl 4.0;

import std;

backend wordpress {
    .host = "127.0.0.1";
    .port = "8080";
    .connect_timeout = 5s;
    .first_byte_timeout = 60s;
    .between_bytes_timeout = 30s;
    .max_connections = 300;
}

sub vcl_recv {
    set req.http.X-Forwarded-Proto = "https";
    set req.http.X-Forwarded-Host = req.http.host;

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

    if (req.url ~ "^/(wp-admin|wp-login|wp-cron\.php|wp-json|xmlrpc\.php)") {
        return (pass);
    }

    if (req.url ~ "(\?add-to-cart|\?order-received|checkout|my-account|\?s=)") {
        return (pass);
    }

    if (req.http.Authorization ||
        req.http.Cookie ~ "(wordpress_logged_in|wp-settings|wp-postpass|comment_author|woocommerce_|PHPSESSID)") {
        return (pass);
    }
}

sub vcl_backend_response {
    set beresp.grace = 10m;
    set beresp.stale_if_error = 24h;

    if (beresp.status ~ "^(301|302|307|308)$") {
        set beresp.ttl = 1h;
    }
}

sub vcl_deliver {
    set resp.http.X-Cache = obj.hits > 0 ? "HIT" : "MISS";
}

The cookie regex is where most troubleshooting time goes. WordPress uses wordpress_logged_in_* for authenticated sessions and wp-settings-* for the per-user settings cookie, while WooCommerce adds woocommerce_items_in_cart and woocommerce_cart_hash as soon as somebody adds a product. Caching a response that carries those cookies is the classic cause of a cart that refuses to empty.

Anonymous commenters are the opposite problem. Their comment_author cookie causes every page load to bypass the cache, so the page can be cached but the cookie stripped in vcl_recv, then re-added in vcl_deliver so WordPress still recognises the commenter.

Connecting Nginx to Varnish and hiding the origin

The public server block becomes a proxy in front of Varnish. Forwarding the client's address matters for WordPress administration, WooCommerce geolocation and any audit plugin that records visitor IPs, so set the forwarding headers carefully rather than letting PHP guess.

server {
    listen 443 ssl http2;
    server_name shop.example.com.au;

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

    location / {
        proxy_pass http://127.0.0.1:6081;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host $host;
        proxy_read_timeout 60s;
        proxy_buffering on;
    }
}

The internal server block on port 8080 keeps your PHP wiring intact, and the trust chain lets WordPress read the real client address through the X-Forwarded-For header.

server {
    listen 127.0.0.1:8080;
    server_name _;
    root /var/www/example;

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

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
    }
}

Lock the origin down with ufw so nothing but the local host can reach the internal block or the Varnish port. If a CDN sits in front of this stack, add set_real_ip_from for the CDN ranges, otherwise every request appears to come from the CDN and your logs lose their meaning.

Content still needs invalidating when you publish. A small hook that sends a PURGE request with the affected URL handles most cases, and it works with the ban mechanism in VCL:

add_action('clean_post_cache', function ($post_id) {
    $url = get_permalink($post_id);
    $ch  = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => 'PURGE',
        CURLOPT_HTTPHEADER   => ['X-Purge-Url: ' . $url],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT      => 5,
    ]);
    curl_exec($ch);
    curl_close($ch);
});

Pair that with a ban() rule in vcl_recv and a matching tag on the backend response, and published updates appear within seconds rather than waiting out the TTL.

Launch checks and Australian deployment realities

Before you move DNS and risk a self-inflicted outage, walk through the configuration methodically.

Before switching traffic:

Once traffic is live:

The local context shapes several decisions. Hosting in the ap-southeast-2 region in Sydney keeps the origin close to the majority of Australian traffic, while a Melbourne or Brisbane provider reduces cost for teams that do not need international reach. Logs deserve attention because IP addresses and customer identifiers captured by Varnish and Nginx are personal information under the Privacy Act 1988 and the Australian Privacy Principles, so set a retention period rather than letting log files grow indefinitely on the disk.

For government and enterprise clients, the ACSC advice on the Essential Eight shapes how you segment the origin, patch it and restrict privileged access, and a separate cache host on a private network answers most of those questions more convincingly than a single box. Finally, remember that the connection between your office and the server is often an NBN service with asymmetric upload speeds. Uploading a large image to wp-content/uploads can take several minutes, which is a workable but slow path for agencies that push galleries weekly, so build that habit around scheduled transfers outside peak hours.

Once the cache is warm, most Australian visitors will never touch PHP at all, and the origin will spend its capacity on the handful of requests that genuinely need it.