- Example VCL template
- 1. Backend definition#
- 2. Purging ACL#
- 3. Host header normalization#
- 4. Httpoxy mitigation#
- 5. Sorting query string parameters#
- 6. Stripping off a trailing question mark#
- 7. Removing marketing parameters from the query string#
- 8. Allow purging#
- 9. Dealing with websockets#
- 10. Piping other non-HTTP content#
- 11. Only cache GET and HEAD requests#
- 12. Remove tracking cookies#
Example VCL template
Varnish’s built-in VCL is very conservative and focuses on not caching stateful and personalized content. By following the HTTP standard for caching rules, Varnish is safe by default. Unfortunately, in many real-life situations where backend servers do not send good caching headers, this will result in a low hit rate.
In this tutorial we’ll present a collection of customizable VCL examples for Varnish. We’ll focus on the individual VCL template features and in the end we’ll bring it all together into a single VCL file.
1. Backend definition#
The first step is to define the backend. This is the origin server where Varnish fetches the content from.
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;
}
Backend connection information#
Every backend definition has a name. In the example above this is server1. The .host and .port attributes contain the address and port number of your backend.
In the example above, the origin, which is probably an Apache or Nginx server, is hosted on the same machine as Varnish. Hence the IP address 127.0.0.1, which corresponds to localhost. Since HTTP clients connect to port 80, the conventional web server is set up to listen to a different port. In the example above, port 8080 is used, and the backend needs to be configured to listen on the same port.
If your origin server is hosted on another server, please adjust the value of the .host attribute. The attribute supports both IP address and hostname values.
The .max_connections attribute will limit the number of simultaneous backend connections that Varnish establishes. If this limit is exceeded, backend requests will start failing.
Health probe#
By defining a health probe, Varnish is made aware of the current health of the backend. The backend is probed at regular intervals and is considered healthy if the backend responds correctly often enough.
Backend health is used first and foremost when load balancing through the vmod_directors module. In these cases, a director load balances between several backends, each representing one server. Backends that are considered sick are not included in the load-balancing rotation.
In VCL, the function std.healthy(backend) can be used to check if a given backend is healthy.
In our sample VCL we send an HTTP HEAD request to the backend. This is done using the .request attribute, which allows us to send a raw HTTP request. This can include any valid HTTP request header.
In the example above the Host: localhost request header is sent by the health probe. If your origin web server is not configured to handle requests for the localhost hostname, please update the value of the Host header in the .request attribute.
The health probe is configured to send a request to the backend every ten seconds. This is done through the .interval attribute.
If the backend doesn’t respond in five seconds , the poll is considered unsuccessful. This is configured through the .timeout attribute.
If three out of five polling attempts fail, the backend is considered sick. If the backend comes online again, it is considered healthy if three of the last five polling attempts succeed.
The polling window is configured through the .window attribute and the .threshold attribute defines the number of (un)successful polling attempts that determine the backend health.
Timeouts#
Varnish will wait for the backend to respond, but does impose timeouts to avoid excessive waiting times.
In the example above the .connect_timeout attribute is set to five seconds , which means Varnish will wait for a maximum of five seconds while attempting to connect to the backend.
The .first_byte_timeout attribute, which is set to 90 seconds in the example, refers to the amount of time Varnish waits after successfully opening a connection before the first byte is received.
And finally the .between_bytes_timeout specifies the maximum time to wait between bytes when reading the response. In this example it is set to two seconds.
These timeouts have default values that can be set by the connect_timeout, first_byte_timeoutand between_bytes_timeout runtime parameters. By specifying them as backend attributes, you have the ability to override them on a per-backend basis.
2. Purging ACL#
One of the features of the sample VCL template is to allow HTTP-based content purging through the PURGE request method. It’s important to avoid unauthorized access to the purge logic.
Therefore, an ACL (Access Control List) should be defined that lists the IP addresses, hostnames and subnets that are allowed to purge content.
In one of the next steps, the ACL will used to protect specific purge resources.
Here’s the VCL code that defines an ACL called purge and only allows access from the local server:
acl purge {
"localhost";
"127.0.0.1";
"::1";
}
3. Host header normalization#
If your Varnish server listens for incoming connections on multiple ports or port numbers other than 80, the port number may end up in the Host header.
For requests to http://example.com:80, the port number will probably be stripped off by your web client, but for other port numbers that won’t be the case.
Because Varnish uses the Host header as part of the object hash, it makes sense to strip off the port number in VCL. Otherwise multiple hashes will be created for what ultimately is the same content. This will reduce the cache capacity and lower the hit rate.
The following VCL code removes the port number from the Host header to avoid this unwanted duplication:
sub vcl_recv {
set req.http.Host = regsub(req.http.Host, ":[0-9]+", "");
}
4. Httpoxy mitigation#
Httpoxy is a set of vulnerabilities that affect certain applications through the Proxy request header.
The general advice is to remove this header to mitigate the impact of httpoxy.
Here’s the VCL code to do this:
sub vcl_recv {
unset req.http.proxy;
}
5. Sorting query string parameters#
Varnish uses both the URL and the Host header to compose the hash that identifies objects in cache. As you’ve seen earlier, Host header normalization is required to avoid cache duplication. However, this also applies to the URL.
Query string parameters, such as, for example /?id=1&gid=5, are also part of the URL, and although their order doesn’t impact the response, it does impact the hash.
That’s why we encourage you to alphabetically sort the query string parameters using the following VCL code:
import std;
sub vcl_recv {
set req.url = std.querysort(req.url);
}
Don’t forget to add import std; to your VCL file. Otherwise the std namespace is not available.
6. Stripping off a trailing question mark#
Here’s another attempt at avoiding cache duplication: removing a trailing question mark.
If your URL is /?, the question mark indicates that query string parameters will follow. But if there are none, the trailing question mark serves no purpose.
The following VCL code will strip off the trailing question mark:
sub vcl_recv {
set req.url = regsub(req.url, "\?$", "");
}
7. Removing marketing parameters from the query string#
A lot of websites use Google Analytics or other marketing tools to analyze their traffic and to track their users.
Although they are beneficial to those who analyze incoming traffic, they are responsible for cache duplication. Removing these parameters has no detrimental effect on the tracking: Google Analytics and other marketing tools do not rely on server-side code and only uses client-side JavaScript.
Here’s how to remove the most common tracking parameters:
sub vcl_recv {
# 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, "[?|&]+$", "");
}
}
8. Allow purging#
Earlier on, we defined an ACL that contains the IP addresses, hostnames and subnets of the clients that are allowed to purge.
Now it’s time to match the client IP address to this ACL , prevent unauthorized clients from purging, and execute return(purge) for authorized clients.
Here’s the VCL code:
sub vcl_recv {
if (req.method == "PURGE") {
if (!client.ip ~ purge) {
return (synth(405, client.ip + " is not allowed to send PURGE requests."));
}
return (purge);
}
}
The !client.ip ~ purge statement will evaluate to true if the client IP address doesn’t match an entry from the purge ACL that we defined earlier. If that is the case, a synthetic response is returned with a 405 Method Not Allowed status.
If the request method equals PURGE and that client IP address matches the purge ACL , return(purge) is used to purge the requested object from the cache.
9. Dealing with websockets#
Although websockets use the same TCP connection as the incoming HTTP request, websockets do not use the HTTP protocol to communicate. Since Varnish only supports HTTP, sending the request directly to the backend using the normal return(pass) procedure will not suffice.
Instead a return(pipe) is required: this opens up the TCP connection to the backend and sends the upgrade request. The websocket data that is returned will not be interpreted by Varnish, and no attempt is made to treat the response as HTTP.
This is the VCL code that is required to make this happen:
sub vcl_recv {
if (req.http.Upgrade ~ "(?i)websocket") {
return (pipe);
}
}
sub vcl_pipe {
if (req.http.upgrade) {
set bereq.http.upgrade = req.http.upgrade;
}
return (pipe);
}
10. Piping other non-HTTP content#
Although the previous VCL snippet was tailored around websockets, there are other situations that grant the use of return(pipe).
When the request method is not one of the following, we can conclude that we’re not dealing with a valid HTTP request:
GETHEADPUTPOSTTRACEOPTIONSPATCHDELETE
Here’s the VCL code to pipe content to the backend when the request method doesn’t match our expectations:
sub vcl_recv {
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);
}
}
It is important to know that this logic is already part of the built-in VCL behavior. However, we typically want to check the method before other logic, and especially if we explicitly return from sub vcl_recv.
If you know that your site only supports a subset of the above, you should consider synthesizing a response in Varnish indicating this:
sub vcl_recv {
if (req.method != "GET" &&
req.method != "HEAD" &&
req.method != "POST" &&
req.method != "OPTIONS") {
return (synth(405, "Method Not Allowed")));
}
}
sub vcl_synth {
if (resp.status == 405) {
set resp.http.Allow = "GET, HEAD, POST, OPTIONS";
set resp.body = "Method not allowed";
return (deliver);
}
}
11. Only cache GET and HEAD requests#
Now that we’re certain that we’re dealing with actual HTTP requests, we can decide to bypass the cache for non-cacheable request methods.
Under normal circumstances, only GET and HEAD requests are cached. Other request methods, such as POST or DELETE, are designed to explicitly change the requested resource.
Why would you cache a resource that will be changed once it is called? That’s why the following VCL example will bypass the cache when a request method other than GET or HEAD is used:
sub vcl_recv {
if (req.method != "GET" && req.method != "HEAD") {
return (pass);
}
}
This code is also part of the built-in VCL. But just like before, this logic might be bypassed by our sample VCL. That’s why it’s important to explicitly include it in the template.
