This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

How to Purge Varnish Cache and Why It’s Important (3 Different Methods)

Updated on November 8, 2023

8 Min Read

purging-varnish-cache-weekly-banner

Varnish is a powerful reverse web proxy accelerator that does wonders by caching HTTP content. It can make your website lightning-fast, speeding up requests by 500-1000 times.

Purging the Varnish cache ensures your website displays up-to-date content and maintains optimal performance.

If you’re a Cloudways user, you’re in luck. Purging the Varnish cache on the Platform is a straightforward process that only takes a few clicks.

For the more technically inclined, there’s the option to utilize the Cloudways API. This lets you interact with your server without opening a web browser. It’s a great way to have more control.

And for those who prefer a manual approach, you can always clear the Varnish cache manually. While it might be a bit more complex, I’ll guide you through the process in this article, so don’t worry.

Let’s dive in and explore these three cache-purging methods!

Brief Overview of Varnish Cache

Varnish Cache is a web application accelerator that functions as a caching HTTP reverse proxy. It operates as an intermediary between your clients (i.e., users) and your web server.

In other words, Varnish Cache can boost the performance of your website by taking on the role of managing and responding to requests for specific content, relieving your web server from the continuous duty of handling such requests.

Why Is It Important to Purge Varnish Cache?

Purging Varnish Cache is essential for ensuring the responsiveness and accuracy of your web content. Over time, cached data can become outdated, making users access stale or incorrect information.

By regularly purging the cache, you guarantee that visitors receive the most up-to-date content, which is critical for dynamic websites and e-commerce platforms.

It also plays a pivotal role in maintaining security by removing any potentially compromised or vulnerable cached content. Additionally, when implementing changes, updates, or bug fixes to your website, purging the cache is crucial to reflect these alterations immediately.

Supercharge Your Website with Cloudways Varnish Hosting!

Experience supreme performance with Cloudways servers featuring Varnish cache and dedicated security measures. Try our 1-Click Varnish Optimized Cloud Server today!

How Does Varnish Cache Purging Work?

Varnish Cache purging operates by executing a “purge,” which involves selecting a specific object from the cache and discarding it, along with any associated variants.

This process can be initiated within the vcl_recv function, effectively removing the object from the cache and freeing up storage space.

The key mechanism here relies on the object’s hash, as it’s utilized for identification, ensuring that the “return (purge)” command eliminates not just the object itself but also any related variants.

When Should You Purge Varnish Cache?

Purging Varnish Cache is necessary when:

  • You make content updates to ensure visitors see the latest version.
  • Bug fixes are implemented to serve corrected content.
  • Security updates are applied to remove potential vulnerabilities.
  • Performance optimization is needed by eliminating unnecessary data.
  • Temporary content, like promotions, must be removed when no longer relevant.

Method 1: Purge Varnish on Cloudways

Now that we’ve looked at what Varnish cache is and how it works let’s see it in action. The first and easiest way to purge the Varnish cache is through the Cloudways Platform.

Let’s see how this works.

  • Log in to your Cloudways account, go to View all ServersServers → Manage Services.

cloudways manage services option

  • To purge the Varnish Cache (i.e., if you have made some changes that you want to check immediately), click on the Purge button.

Method 2: Purge Varnish Using Cloudways API

Another method is to purge the Varnish Cache using the Cloudways API. Before we proceed, keep in mind that this method requires some basic understanding of coding.

We have a separate guide on how to use the Cloudways API. You might find it helpful.

Anyway, let’s get on with the steps!

Step#1: Obtaining the API Key

The first order of business is the generation of the API Key from here. Simply click on the Regenerate Key button to get your API secret key.

Step#2: Writing the Code

Once you get your secret key, it is time to do a bit of coding. The code starts with the creation of the Cloudways API client class.

<?php

class CloudwaysAPIClient {
const API_URL = "https://api.cloudways.com/api/v1";
var $auth_key;
var $auth_email;
var $accessToken;
function CloudwaysAPIClient($key, $email) {
    $this->auth_key = $key;
    $this->auth_email = $email;
    $this->prepare_access_token();
}
function prepare_access_token() {
    $data = ['email' => $this->auth_email,
              'api_key' => $this->auth_key
            ];
    $response = $this->request('POST', '/oauth/access_token', $data);
    $this->accessToken = $response->access_token;
}

function request($method, $url, $post = []) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_URL, self::API_URL . $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);      
    do {
        if ($this->accessToken) {
           curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $this->accessToken]);
        }

        //Set Post Parameters
        $encoded = '';
        if (count($post)) {
            foreach ($post as $name => $value) {
                $encoded .= urlencode($name) . '=' . urlencode($value) . '&';
            }

            $encoded = substr($encoded, 0, strlen($encoded) - 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
            curl_setopt($ch, CURLOPT_POST, 1);
        }

        $output = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);      

        # ACCESS TOKEN HAS EXPIRED, so regenerate and retry

        if ($httpcode == '401') {
            $this->prepare_access_token();    
        }

    } while ($httpcode == '401');
   if ($httpcode != '200') {
        die('An error occurred code: ' . $httpcode . ' output: ' . substr($output, 0, 10000));
    }

    curl_close($ch);
    return json_decode($output);
}
}
?>

This is the basic client class. More functions could be added to the class as the need arises. For now, focus on the prepare_access_token() function that is called inside the constructor.

Step#3: Setting up Authentication

At Cloudways, we’ve streamlined the authentication process using OAuth. With OAuth, the process becomes secure and user-friendly. It works like this:

Client sends request with API key

Client ——-> <secret-unique-API-key> ——> API

On successful validation, API returns an access token

Client <——-  <unique-API-access-token> <—– API

The client uses the unique access token inside the header(‘Authorization: Bearer <unique-api-access-token>’) to make all subsequent requests

Client  ——-> <unique-API-access-token> + request —–> API

In the API class, the prepare_access_token() takes care of this process automatically. It calls the /oauth/access_token endpoint using the request function and sets the accessToken variable to a valid access token.

The request function is generic and will handle all other endpoints that might be added further. It will also automatically refresh expired OAuth access token (the token expires after 3600 seconds of inactivity) and retry the request.

Now that the boilerplate is out of the way, I can start adding more functionality.

I will add one more function to the class (inside CloudwaysAPI.class.php) for listing the servers.

function get_servers() {
    $response = $this->request('GET', '/server');
    if ($response->status === true) {
        return $response->servers;
    }
    return false;
}

This function will call the API using the generic request function and return a list of servers along with their information.

At this point, it is time to create the actual script. I could add the code for the script inside CloudwaysAPI.class.php file. However, keeping future development purposes in view, I will keep them separate.

Create the following file and replace the API key with the one generated above. Also, replace the email.

Step#4: Creating the Purge_varnish.php Script

<?php
include 'CloudwaysAPI.class.php';
$api_key = '<your-key-generated-from-cloudways-api>';
$email = '<your-email>';
$cw_api = new CloudwaysAPIClient($api_key, $email);
$servers = $cw_api->get_servers();
foreach($servers as $server) {
echo 'ID -> ' . $server->id;
echo ', SERVER -> ' . $server->label;
# $cw_api->service_varnish($server->id, 'purge');
    # echo ', cache purged';
}
?>

I hope that the script is self-explanatory. I include CloudwayAPI.class.php (created earlier) and create a CloudwaysAPIClient object using my credentials (email and API key).

include 'CloudwaysAPI.class.php';
$api_key = '<your-key-generated-from-cloudways-api>';
$email = '<your-email>';
$cw_api = new CloudwaysAPIClient($api_key, $email);

At this point, OAuth has been taken care of and I can use start using the cw_api object to make the API calls.

Next, I will call the API to get the list of servers and will loop through the list.

$servers = $cw_api->get_servers();
foreach($servers as $server) {
echo 'ID -> ' . $server->id;
echo ', SERVER -> ' . $server->label;
}

Ignore the commented-out lines for now, as I have not implemented the service_varnish function yet.

Running this script will output the server ID along with its server label/name.

> php -f purge_varnish.php

ID -> 58430, SERVER -> myTestServer

The get_servers function gives all the information that I need for purging the Varnish cache, including server ID.

Now, let’s add another API endpoint. Add the following function to your CloudwaysAPIClient class inside CloudwayAPI.class.php:

function service_varnish($server_id, $action) {
    $actions = ['enable', 'disable', 'purge'];
    if (in_array($action, $actions)) {
        $data = ['server_id' => $server_id,
                 'action' => $action
             ];
        return $this->request('POST', '/service/varnish', $data);
    }
    return false;
}

Uncomment the following lines from the purge_varnish.php file

$cw_api->service_varnish($server->id, 'purge');
echo ', cache purged';

At this point, running the script will purge Varnish cache for all of the servers on the list. For a specific server, just use the server name:

if ($server->label == 'myTestServer') {
    $cw_api->service_varnish($server->id, 'purge');
    echo ', cache purged';
}

Step#5: Scheduling the Cron Job

Now add a cron job for the script we just created. In the Cloudways Platform, you can use the application’s Cron Job Management page. We have a guide on how to create Cron Jobs on Cloudways. You should definitely check it out for more clarity.

In the common settings dropdown, choose once a week, and enter the script name (relative to your public_html folder).

At this stage, we’ve accomplished the main goals of this tutorial. You’re all set to refresh your servers’ Varnish Cache weekly, and you have the necessary groundwork to work with CloudwaysAPI.

Something Extra

I will now ensure that the cron job was successfully added by adding the following function to the CloudwaysAPIClient class. This retrieves the cron job list for the servers:

function get_cron_list($server_id, $app_id) {
    $data = ['server_id' => $server_id,
             'app_id' => $app_id
            ];
    $qry_str = "?";
    foreach ($data as $name => $value) {
        $qry_str .= urlencode($name) . '=' . urlencode($value) . '&';
    }
    return $this->request('GET', '/app/manage/cronList'. $qry_str);
}

Also, I will modify the script:

$servers = $cw_api->get_servers();
foreach($servers as $server) {
foreach($server->apps as $app){
var_dump($cw_api->get_cron_list($server->id, $app->id));
}
}

This will return information about the Cron job.

Method 3: Purge Vanish Cache Manually

Here are the three distinct methods for manually purging Varnish Cache:

1. Varnish Cache Restart

To efficiently clear the entire Varnish cache, initiate a Varnish cache restart. Execute the following command:

service varnish restart

This action promptly resets the entire cache on your server.

2. Cache Purge via VCL Configuration

The second approach available is to use the Varnish Configuration Language (VCL) for precise cache purging of specific items.

Create an Access Control List (ACL) within the default VCL file located at /etc/varnish/default.vcl. Here’s an illustrative example:

acl purge_acl {

    "localhost";

    "1xx.2xx.3x.0"/24;

}

sub vcl_recv {

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

        if (!client.ip ~ purge_acl) {

            return(synth(405,"Not authorized."));

        }

        return (purge);

    }

}

To selectively purge a particular URL, employ cURL:

curl -X PURGE URL-to-PURGE

3. Cache Purge via Command Line

Another method is to purge the cache directly from the command line. For a comprehensive cache purge, use:

varnishadm 'ban req.url ~ .'

To target specific domains or URLs:

varnishadm -T 192.168.1.100:6082 -S /etc/varnish/secret "ban req.http.host ~ www.example.com && req.url http://www.example.com"

For the removal of all .html pages within a domain:

varnishadm -T 192.168.1.101:6082 -S /etc/varnish/secret "ban req.http.host ~ www.example.com && req.url .HTML"

These methods offer diverse approaches for manually clearing Varnish cache, tailored to various needs.

Summary

I hope you found this guide on Varnish purge cache helpful. In this blog, I shared with you three distinct methods of clearing the Varnish cache.

The most straightforward method to clear the Varnish cache is by using a one-click button. Cloudways stands out by offering a one-click Varnish cache-clearing feature, which is not commonly available among many other cloud providers.

If you have a question or would like to add to the discussion, please leave a comment.

Q1. What does the Varnish Cache do?

Varnish cache speeds up websites by storing and serving frequently requested content, reducing the need to fetch data from the web server.

Q2. How do you refresh the Varnish Cache?

You can refresh Varnish by restarting the Varnish service, writing rules in Varnish Configuration Language (VCL) for specific content, or using command-line tools like ‘varnishadm’.

Q3. How do I flush the Varnish Cache?

To flush the Varnish cache, you can restart the Varnish service or use VCL rules to purge specific content. Command-line tools like ‘varnishadm’ can also help clear the cache.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Abdul Rehman

Abdul is a tech-savvy, coffee-fueled, and creatively driven marketer who loves keeping up with the latest software updates and tech gadgets. He's also a skilled technical writer who can explain complex concepts simply for a broad audience. Abdul enjoys sharing his knowledge of the Cloud industry through user manuals, documentation, and blog posts.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now