Skip to content

Instantly share code, notes, and snippets.

@pbowyer
Created August 13, 2020 21:09
Show Gist options
  • Save pbowyer/8822ab1d61fc209056f0f6bc694319f7 to your computer and use it in GitHub Desktop.
Save pbowyer/8822ab1d61fc209056f0f6bc694319f7 to your computer and use it in GitHub Desktop.
# Marker to tell the VCL compiler that this VCL has been written with the
# 4.0 or 4.1 syntax.
vcl 4.1;
import std;
# Default backend definition. Set this to point to your content server.
backend default {
.host = "127.0.0.1";
.port = "8080";
}
sub vcl_recv {
# Happens before we check if we have this in cache already.
#
# Typically you clean up the request here, removing cookies you don't need,
# rewriting the request, etc.
# If HTTPS, the backend needs to know
if (std.port(server.ip) == 443) {
set req.http.X-Forwarded-Proto = "https";
}
# If not HTTPS, redirect to HTTPS
if (req.http.X-Forwarded-Proto !~ "https") {
return (synth(850, "Moved Permanently"));
}
# set to Gzip, deflate or remove entirely
if (req.http.Accept-Encoding) {
if (req.url ~ "\.(jpg|jpeg|png|gif|gz|tgz|bz2|tbz|mp3|mp4|ogg)$") {
unset req.http.Accept-Encoding;
} elsif (req.http.Accept-Encoding ~ "gzip") {
set req.http.Accept-Encoding = "gzip";
} elsif (req.http.Accept-Encoding ~ "deflate") {
set req.http.Accept-Encoding = "deflate";
} else {
unset req.http.Accept-Encoding;
}
}
return(hash);
}
sub vcl_backend_response {
# Happens after we have read the response headers from the backend.
#
# Here you clean the response headers, removing silly Set-Cookie headers
# and other mistakes your backend does.
set beresp.grace = 2m;
set beresp.keep = 8m;
# We clear the Varnish cache when needed, so keep here for longer
set beresp.ttl = 1d;
# Do not Gzip image files in Varnish
if (beresp.http.url ~ "\.(jpg|jpeg|png|gif|gz|tgz|bz2|tbz|mp3|mp4|ogg|swf)$") {
set beresp.do_gzip = false;
}
else {
set beresp.do_gzip = true;
set beresp.http.X-Cache = "ZIP";
}
# GZip the cached content if possible
if (beresp.http.content-type ~ "text") {
set beresp.do_gzip = true;
}
}
sub vcl_deliver {
# Happens when we have all the pieces we need, and are about to send the
# response to the client.
#
# You can do accounting or modifying the final object here.
}
sub vcl_synth {
if (resp.status == 301 || resp.status == 302) {
set resp.http.location = resp.reason;
set resp.reason = "Moved";
return (deliver);
}
# Synthetic response for redirecting to HTTPS
if(resp.status == 850) {
set resp.http.Location = "https://" + req.http.host + req.url;
set resp.status = 301;
return(deliver);
}
}
sub vcl_hash {
# We want to cache http and https separately, so we can cache the redirects
hash_data(req.http.X-Forwarded-Proto);
hash_data(req.http.X-IsLoggedIn);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment