Make W3 Total Cache “Empty All Caches” function purge varnish

Right now, when I perform “Empty All Caches” it doesn’t send a PURGE request to varnish. The result is that varnish isn’t being refreshed. Is there a way that I can make varnish purge it’s cache when choosing “Empty All Caches”? Is there a way that I can hook into W3 Total Cache “Empty All Caches”?

Related posts

Leave a Reply

2 comments

  1. A simple solution could be to check when you click the “empty all cache” Button with $_GET Like this:

    function wpse_16722_purge_varnish() {
        // Is the button submitted, Get the value
        $purge = isset( $_GET['w3tc_note'] ) ? trim( $_GET['w3tc_note'] ) : '';
    
        // Security-check, user can edit settings
        // And the button "Empty all cache" is submitted
        if( current_user_can('manage_options') && $purge == 'flush_all' ) {
    
            // Maybe there is a better way to clear the cache 
            // in varnish, i found this on php.net
            // Change this to match your Varnish-setup
    
            $fp = fsockopen( "127.0.0.1", "80", $errno, $errstr, 2 );
    
            if ( ! $fp ) {
                echo = "$errstr ($errno)<br />n";
            } else {
                $out = "PURGE /alain HTTP/1.0rn";
                $out .= "Host: giantdorks.orgrn";
                $out .= "Connection: Closernrn";
    
                fwrite( $fp, $out );
    
                while ( ! feof( $fp ) ) {
                    echo fgets( $fp, 128 );
                }
                fclose( $fp );
            }    
        }
    }
    add_action('admin_head', 'wpse_16722_purge_varnish');
    

    The Varnish Configuration Language (VCL) also has the url purging function. It’s accessible via the purge_url(url_pattern) function.

    acl purge_acl {
        "localhost";
        "some.hostname.ext";
        "154.120.2.33";
    }
    sub vcl_recv {
        if(req.request == "flush_all") {
            if(!client.ip ~ purge_acl) {
                error 405 "Not allowed";
            } else {
                purge_url(req.url);
                error 200 "Purged";
            }
        }
    }
    

    The script above has the normal proxy/cache behaviour for request methods like GET & POST. But when a user connects via the “flush_all” method, the page is purged.

  2. It appears that the problem is known to W3 Total Cache and that it may be fixed soon. Assuming that you have SSH access, open a new client and run:

    varnishadm -T 127.0.0.1:6082 url.purge .
    

    This will force the cache to be refreshed (Please note that I do not use Varnish so this code is untested.) I found this on the garron Site.

    Cheers,
    Joe