Purge Varnish Cache with Bash

Ever wondered how to clear out the cache for a specific URL or even your whole website when you’re using Varnish? Sometimes it’s necessary to expire the cache on a URL, like a stylesheet or JavaScript file before Varnish thinks it’s done. This can be useful when you’re making changes to your website and need to see the change immediately, instead of waiting for the cache to expire.

Luckily, it’s easy to purge varnish cache from the command line. Varnish (on implementations that have the VCL to make it work) allows you to send a special HTTP request with the PURGE verb in order to expire/purge a resource immediately. For security reasons, many implementations lock this down to only allowing it from localhost, so that no random user can purge the cache which could cause quite a hit on the server.

At a minimum, that is what you need to get purging to work in Varnish. The snippet above will allow PURGE requests from localhost (127.0.0.1 / ::1) and people in the 192.168.55.0/24 subnet, as an example. This particular example is straight from the Varnish Documentation.

 

But how to I invalidate a page?

Okay, so now purging should work… but how do I purge the cache? At the minimum, you need to send a HTTP request to the URL you want to invalidate using the HTTP verb “PURGE”, like this:

Or, you can do it with a simple bash script that you run from an SSH session on your website’s box (or wherever Varnish is located)

All you have to do is set it to be executable

and then call it with a URL:

The first example will invalidate a specific file/url, and the second will invalidate the entire website.