Example VCL template·续

Varnish’s built-in VCL behavior bypasses the cache when a Cookie request header is detected. As mentioned at the start of this tutorial: Varnish is very conservative when it comes to its standard behavior.

Because cookies imply a level of personalization, caching private data is tricky without knowing the purpose of these cookies.

However, tracking cookies aren’t really an issue: they are handled by the browser and can safely be removed by Varnish to ensure a better hit rate.

Google Analytics#

The following VCL code will remove tracking cookies set by Google Analytics:

sub vcl_recv {
    set req.http.Cookie = regsuball(req.http.Cookie, "(__utm|_ga|_opt)[a-z_]*=[^;]+(; )?", "");
}

HubSpot#

The following VCL code will remove tracking cookies set by HubSpot:

sub vcl_recv {
    set req.http.Cookie = regsuball(req.http.Cookie, "(__)?hs[a-z_\-]+=[^;]+(; )?", "");
    set req.http.Cookie = regsuball(req.http.Cookie, "hubspotutk=[^;]+(; )?", "");
}

Hotjar#

The following VCL code will remove tracking cookies set by Hotjar:

sub vcl_recv {
    set req.http.Cookie = regsuball(req.http.Cookie, "_hj[a-zA-Z]+=[^;]+(; )?", "");
}

Google advertising products#

The following VCL code will remove tracking cookies set by Google advertising products:

sub vcl_recv {
    set req.http.Cookie = regsuball(req.http.Cookie, "(NID|DSID|__gads|GED_PLAYLIST_ACTIVITY|ACLK_DATA|ANID|AID|IDE|TAID|_gcl_[a-z]*|FLC|RUL|PAIDCONTENT|1P_JAR|Conversion|VISITOR_INFO1[a-z_]*)=[^;]+(; )?", "");
}

Other tracking cookies#

The list of tracking cookies that was featured in this tutorial only covers some of the big analytics and advertising tools. You might use other tools, which use other cookies.

If your website features other tracking cookies, please strip them off using the code below:

sub vcl_recv {
    set req.http.Cookie = regsuball(req.http.Cookie, "cookiename=[^;]+(; )?", "");
}

Replace cookiename with the name of the tracking cookie you want to remove, or a regular expression pattern that matches multiple names.

Remove semicolon prefix#

After you have stripped off all tracking cookies, you might be left with a ; prefix as the remaining value of the Cookie header. If that is the case, it needs to be removed as well:

sub vcl_recv {
    set req.http.Cookie = regsuball(req.http.Cookie, "^;\s*", "");
}

Remove empty cookies#

When stripping off tracking cookies results in an empty string, or a collection of whitespace characters, you can safely remove the entire Cookie header as illustrated below:

sub vcl_recv {
    if (req.http.cookie ~ "^\s*$") {
        unset req.http.cookie;
    }
}

Being able to remove the entire Cookie header means that there are no functional cookies left and that the entire page is cacheable.

13. Setting the X-Forwarded-Proto header#

The X-Forwarded-Proto header is used to transmit the request protocol that was used by the client. Varnish can accept incoming requests via HTTP or HTTPS. However, if another proxy in front of Varnish uses another protocol, the X-Forwarded-Proto can be used to transmit the original protocol to the server.

The VCL snippet below sets the X-Forwarded-Proto header if it’s not set. The header will be X-Forwarded-Proto: https if the request was received on port 443, and X-Forwarded-Proto: http for any port:

import std;

sub vcl_recv {
    if (!req.http.X-Forwarded-Proto) {
        if(std.port(server.ip) == 443) {
            set req.http.X-Forwarded-Proto = "https";
        } else {
            set req.http.X-Forwarded-Proto = "http";
        }
    }
}

sub vcl_hash {
    hash_data(req.http.X-Forwarded-Proto);
}

By default Varnish has no awareness of the requested protocol when it performs a cache lookup. This might lead to mixed content or even a redirect loop when an HTTP to HTTPS redirection ends up getting cached.

That’s why it makes sense to add the value of the X-Forwarded-Proto header to the hash when requesting the object from cache. This will ensure that each page has an HTTP version and an HTTPS version stored in cache.

13. Caching static content#

By now you should be aware that Varnish doesn’t cache when a Cookie request header is presented unless you write the appropriate VCL.

But for static content, such as images, CSS files, JavaScript files and other similar resources, we can force them to be cached. This also means stripping off any potential cookies.

The following VCL snippet will force caching for requests matching the following file extensions:

  • 7z
  • avi
  • bmp
  • bz2
  • css
  • csv
  • doc
  • docx
  • eot
  • flac
  • flv
  • gif
  • gz
  • ico
  • jpeg
  • jpg
  • js
  • less
  • mka
  • mkv
  • mov
  • mp3
  • mp4
  • mpeg
  • mpg
  • odt
  • ogg
  • ogm
  • opus
  • otf
  • pdf
  • png
  • ppt
  • pptx
  • rar
  • rtf
  • svg
  • svgz
  • swf
  • tar
  • tbz
  • tgz
  • ttf
  • txt
  • txz
  • wav
  • webm
  • webp
  • woff
  • woff2
  • xls
  • xlsx
  • xml
  • xz
  • zip

sub vcl_recv { if (req.url ~ "^[^?].(7z|avi|bmp|bz2|css|csv|doc|docx|eot|flac|flv|gif|gz|ico|jpeg|jpg|js|less|mka|mkv|mov|mp3|mp4|mpeg|mpg|odt|ogg|ogm|opus|otf|pdf|png|ppt|pptx|rar|rtf|svg|svgz|swf|tar|tbz|tgz|ttf|txt|txz|wav|webm|webp|woff|woff2|xls|xlsx|xml|xz|zip)(\?.)?$") { unset req.http.Cookie; unset req.http.Authorization # Only keep the following if VCL handling is complete return(hash); } }

sub vcl_backend_response {
    if (bereq.url ~ "^[^?]*\.(7z|avi|bmp|bz2|css|csv|doc|docx|eot|flac|flv|gif|gz|ico|jpeg|jpg|js|less|mka|mkv|mov|mp3|mp4|mpeg|mpg|odt|ogg|ogm|opus|otf|pdf|png|ppt|pptx|rar|rtf|svg|svgz|swf|tar|tbz|tgz|ttf|txt|txz|wav|webm|webp|woff|woff2|xls|xlsx|xml|xz|zip)(\?.*)?$") {
        unset beresp.http.Set-Cookie;
        set beresp.ttl = 1d;
    }
}

This means that the Cookie and Authorization request headers are stripped off and the request is immediately looked up in cache. In case of a cache miss, a potential Set-Cookie response header is stripped off as well and the Time-To-Live of the object is set to a day.

14. ESI support#

When your application supports Edge Side Includes (ESI) , we need to write some VCL code to enable ESI parsing.

The idea is that we announce ESI support through the Surrogate-Capability: key=ESI/1.0 request header. When the application notices this, it should send a corresponding Surrogate-Control header that also contains ESI/1.0. When Varnish sees this Surrogate-Control response header, it will enable ESI parsing as illustrated below:

sub vcl_recv {
    set req.http.Surrogate-Capability = "key=ESI/1.0";
}

sub vcl_backend_response {
    if (beresp.http.Surrogate-Control ~ "ESI/1.0") {
        unset beresp.http.Surrogate-Control;
        set beresp.do_esi = true;
    }
}

15. Setting grace mode#

When content has expired from the cache, Varnish needs to revalidate that content with the origin server. This usually involves a backend fetch, and the client that requested the content has to wait until the origin responds. This could potentially be detrimental to the user experience.

Thanks to grace mode , Varnish can asynchronously revalidate content while serving the stale version to the client.

The standard grace value is set to ten seconds , which means content will be asynchronously revalidated until an object is ten seconds past the expiration of its Time-To-Live.

If you want to change this value in your VCL file, you can use the following code:

import std;

sub vcl_recv {
    if (std.healthy(req.backend_hint)) {
        set req.grace = 10s;
    }
}

sub vcl_backend_response {
    set beresp.grace = 6h;
}

This example will set the grace value to six hours , but will only use ten seconds of grace at request time when the backend is healthy.

If the origin server is down, Varnish will still serve an outdated version of the object for another six hours, which can potentially be a lifesaver. When the origin recovers, the grace value of ten seconds will be used again.

Keep in mind that determining the health of a backend is only possible when the backend definition is linked to health probe.

16. Putting it all together#

Here’s the all-in-one VCL file that has all the previous snippets:

vcl 4.1;

import std;

backend server1 {
    .host = "127.0.0.1";
    .port = "8080";
    .max_connections = 100;
    .probe = {
        .request =
            "HEAD / HTTP/1.1"
            "Host: localhost"
            "Connection: close"
            "User-Agent: Varnish Health Probe";
        .interval  = 10s;
        .timeout   = 5s;
        .window    = 5;
        .threshold = 3;
    }
    .connect_timeout        = 5s;
    .first_byte_timeout     = 90s;
    .between_bytes_timeout  = 2s;
}

acl purge {
    "localhost";
    "127.0.0.1";
    "::1";
}

sub vcl_recv {
    set req.http.Host = regsub(req.http.Host, ":[0-9]+", "");
    unset req.http.proxy;
    set req.url = std.querysort(req.url);
    set req.url = regsub(req.url, "\?$", "");
    set req.http.Surrogate-Capability = "key=ESI/1.0";

    if (std.healthy(req.backend_hint)) {
        set req.grace = 10s;
    }

    if (!req.http.X-Forwarded-Proto) {
        if(std.port(server.ip) == 443) {
            set req.http.X-Forwarded-Proto = "https";
        } else {
            set req.http.X-Forwarded-Proto = "https";
        }
    }

    if (req.http.Upgrade ~ "(?i)websocket") {
        return (pipe);
    }

    # Remove tracking query string parameters used by analytics tools
    if (req.url ~ "(\?|&)(_branch_match_id|_bta_[a-z]+|_bta_c|_bta_tid|_ga|_gl|_ke|_kx|campid|cof|customid|cx|dclid|dm_i|ef_id|epik|fbclid|gad_source|gbraid|gclid|gclsrc|gdffi|gdfms|gdftrk|hsa_acc|hsa_ad|hsa_cam|hsa_grp|hsa_kw|hsa_mt|hsa_net|hsa_src|hsa_tgt|hsa_ver|ie|igshid|irclickid|matomo_campaign|matomo_cid|matomo_content|matomo_group|matomo_keyword|matomo_medium|matomo_placement|matomo_source|mc_[a-z]+|mc_cid|mc_eid|mkcid|mkevt|mkrid|mkwid|msclkid|mtm_campaign|mtm_cid|mtm_content|mtm_group|mtm_keyword|mtm_medium|mtm_placement|mtm_source|nb_klid|ndclid|origin|pcrid|piwik_campaign|piwik_keyword|piwik_kwd|pk_campaign|pk_keyword|pk_kwd|redirect_log_mongo_id|redirect_mongo_id|rtid|s_kwcid|sb_referer_host|sccid|si|siteurl|sms_click|sms_source|sms_uph|srsltid|toolid|trk_contact|trk_module|trk_msg|trk_sid|ttclid|twclid|utm_[a-z]+|utm_campaign|utm_content|utm_creative_format|utm_id|utm_marketing_tactic|utm_medium|utm_source|utm_source_platform|utm_term|vmcid|wbraid|yclid|zanpid)=") {
        set req.url = regsuball(req.url, "(_branch_match_id|_bta_[a-z]+|_bta_c|_bta_tid|_ga|_gl|_ke|_kx|campid|cof|customid|cx|dclid|dm_i|ef_id|epik|fbclid|gad_source|gbraid|gclid|gclsrc|gdffi|gdfms|gdftrk|hsa_acc|hsa_ad|hsa_cam|hsa_grp|hsa_kw|hsa_mt|hsa_net|hsa_src|hsa_tgt|hsa_ver|ie|igshid|irclickid|matomo_campaign|matomo_cid|matomo_content|matomo_group|matomo_keyword|matomo_medium|matomo_placement|matomo_source|mc_[a-z]+|mc_cid|mc_eid|mkcid|mkevt|mkrid|mkwid|msclkid|mtm_campaign|mtm_cid|mtm_content|mtm_group|mtm_keyword|mtm_medium|mtm_placement|mtm_source|nb_klid|ndclid|origin|pcrid|piwik_campaign|piwik_keyword|piwik_kwd|pk_campaign|pk_keyword|pk_kwd|redirect_log_mongo_id|redirect_mongo_id|rtid|s_kwcid|sb_referer_host|sccid|si|siteurl|sms_click|sms_source|sms_uph|srsltid|toolid|trk_contact|trk_module|trk_msg|trk_sid|ttclid|twclid|utm_[a-z]+|utm_campaign|utm_content|utm_creative_format|utm_id|utm_marketing_tactic|utm_medium|utm_source|utm_source_platform|utm_term|vmcid|wbraid|yclid|zanpid)=[-_A-z0-9+(){}%.*]+&?", "");
        set req.url = regsub(req.url, "[?|&]+$", "");
    }

    if (req.method == "PURGE") {
        if (!client.ip ~ purge) {
            return (synth(405, client.ip + " is not allowed to send PURGE requests."));
        }
        return (purge);
    }

    if (req.method != "GET" &&
        req.method != "HEAD" &&
        req.method != "PUT" &&
        req.method != "POST" &&
        req.method != "TRACE" &&
        req.method != "OPTIONS" &&
        req.method != "PATCH" &&
        req.method != "DELETE") {
        return (pipe);
    }

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

    if (req.url ~ "^[^?]*\.(7z|avi|bmp|bz2|css|csv|doc|docx|eot|flac|flv|gif|gz|ico|jpeg|jpg|js|less|mka|mkv|mov|mp3|mp4|mpeg|mpg|odt|ogg|ogm|opus|otf|pdf|png|ppt|pptx|rar|rtf|svg|svgz|swf|tar|tbz|tgz|ttf|txt|txz|wav|webm|webp|woff|woff2|xls|xlsx|xml|xz|zip)(\?.*)?$") {
        unset req.http.Cookie;
        return(hash);
    }

    set req.http.Cookie = regsuball(req.http.Cookie, "(__utm|_ga|_opt)[a-z_]*=[^;]+(; )?", "");
    set req.http.Cookie = regsuball(req.http.Cookie, "(__)?hs[a-z_\-]+=[^;]+(; )?", "");
    set req.http.Cookie = regsuball(req.http.Cookie, "hubspotutk=[^;]+(; )?", "");
    set req.http.Cookie = regsuball(req.http.Cookie, "_hj[a-zA-Z]+=[^;]+(; )?", "");
    set req.http.Cookie = regsuball(req.http.Cookie, "(NID|DSID|__gads|GED_PLAYLIST_ACTIVITY|ACLK_DATA|ANID|AID|IDE|TAID|_gcl_[a-z]*|FLC|RUL|PAIDCONTENT|1P_JAR|Conversion|VISITOR_INFO1[a-z_]*)=[^;]+(; )?", "");
    set req.http.Cookie = regsuball(req.http.Cookie, "^;\s*", "");

    if (req.http.cookie ~ "^\s*$") {
        unset req.http.cookie;
    }
}

sub vcl_hash {
    hash_data(req.http.X-Forwarded-Proto);
}

sub vcl_backend_response {
    if (bereq.url ~ "^[^?]*\.(7z|avi|bmp|bz2|css|csv|doc|docx|eot|flac|flv|gif|gz|ico|jpeg|jpg|js|less|mka|mkv|mov|mp3|mp4|mpeg|mpg|odt|ogg|ogm|opus|otf|pdf|png|ppt|pptx|rar|rtf|svg|svgz|swf|tar|tbz|tgz|ttf|txt|txz|wav|webm|webp|woff|woff2|xls|xlsx|xml|xz|zip)(\?.*)?$") {
        unset beresp.http.Set-Cookie;
        set beresp.ttl = 1d;
    }

    if (beresp.http.Surrogate-Control ~ "ESI/1.0") {
        unset beresp.http.Surrogate-Control;
        set beresp.do_esi = true;
    }

    set beresp.grace = 6h;
}