All Linux HowTo's

How to Purge Varnish Cache Remotely

Share This:

This article explains how to purge a Varnish cache from a remote system. For example, if your proxy server is on a different physical server from your web server, you may find it hard to devise a trigger for a Varnish cache flush (purge). This article explains how you can trigger a Varnish flush from a trusted location other than the proxy server. I’ve used this website as a source “https://www.varnish-cache.org/docs/3.0/tutorial/purging.html”.

In this example, the Varnish proxy is running on the server “cache.agix.local”.

First, add the following to you Varnish config file (default.vcl by default):

# I'm cache.agix.local

acl purge {
        "localhost";
        "192.168.0.0"/16;
        "1.2.3.4";
}

sub vcl_recv {
        # allow PURGE from localhost, 192.168./16 and 1.2.3.4.

        if (req.request == "PURGE") {
                if (!client.ip ~ purge) {
                        error 405 "Not allowed.";
                }
                return (lookup);
        }
}

sub vcl_hit {
        if (req.request == "PURGE") {
                purge;
                ban("req.url ~ "+req.url);
                error 200 "Purged.";
        }
}

sub vcl_miss {
        if (req.request == "PURGE") {
                purge;
                ban("req.url ~ "+req.url);
                error 200 "Purged.";
        }
}

Next create a script on a remote system as follows – “/var/www/html/remote_varnish_purge.php”. Note that the remote system must either be in the “192.168./16” network or have the IP address “1.2.3.4” or you should edit the IP addresses in the “purge” ACL above:

<?php
# I'm "/var/www/html/remote_varnish_purge.php" on host "1.2.3.4".'
# AGIX: Script to flush Varnish cache on remote system.
####
$curl = curl_init("http://cache.agix.local/");
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PURGE");
curl_exec($curl);
?>

Test it:

php -f /var/www/html/remote_varnish_purge.php

At this point you can run it manually, schedule it via cron or trigger it via a web app.

Similar Posts: