Skip to content

Instantly share code, notes, and snippets.

@guelau
Last active November 14, 2018 10:46
Show Gist options
  • Save guelau/5728bc59ea6b8c4d6787522e60f9e19e to your computer and use it in GitHub Desktop.
Save guelau/5728bc59ea6b8c4d6787522e60f9e19e to your computer and use it in GitHub Desktop.
Varnish Check
backend default {
.host = "127.0.0.1";
.port = "8080";
}
sub vcl_recv {
if (req.http.host ~ "^cdn\.myapiservice\.com") {
set req.http.host = "api.myapiservice.com";
set req.url = regsub(req.url, "^/", "/v1/images/");
}
if (!req.backend.healthy||req.http.host ~ "^cdn\.myapiservice\.com"||req.url ~ "^.*v1/images/.*") {
if (req.request == "GET" ||
# req.request == "OPTIONS" ||
req.request == "HEAD"
) {
unset req.http.Authorization;
unset req.http.Cookie;
return (lookup);
}
}
}
sub vcl_deliver {
if (obj.hits > 0) {
set resp.http.X-Varnish-Cache = "HIT";
}
else {
set resp.http.X-Varnish-Cache = "MISS";
}
return (deliver);
}
sub vcl_fetch {
#set beresp.ttl = 6s;
if (beresp.ttl <= 0s) {
set beresp.http.X-Cacheable = "NO:Not Cacheable";
/*
* Mark as "Hit-For-Pass" for the next 2 minutes
*/
/** **/
set beresp.http.X-Varnish-Api = "API";
unset beresp.http.set-cookie;
set beresp.ttl = 120 s;
return (deliver);
/** **/
/**
return (hit_for_pass);
**/
} elsif (req.http.Cookie ~ "(UserID|_session)") {
set beresp.http.X-Cacheable = "NO:Got Session";
return(hit_for_pass);
} elsif (beresp.http.Cache-Control ~ "private") {
set beresp.http.X-Cacheable = "NO:Cache-Control=private";
return(hit_for_pass);
}
if (beresp.status >= 500 && beresp.status <= 599) {
set beresp.http.X-Cacheable = "NO: 500";
return(hit_for_pass);
}
if (beresp.status >= 400 && beresp.status <= 499) {
set beresp.http.X-Cacheable = "NO: 400";
set beresp.ttl = 0s;
return (hit_for_pass);
}
if (req.http.host ~ "^cdn\.myapiservice\.com"||req.url ~ "^.*v1/images/.*") {
set beresp.ttl = 730h;
unset beresp.http.set-cookie;
return (deliver);
}
return (deliver);
}
sub vcl_error {
set obj.http.Content-Type = "application/json";
synthetic {"{error: "} + obj.status + " " + obj.response + {"}"};
return (deliver);
}
sub vcl_hit {
if (req.request == "PURGE") {
set obj.ttl = 0s;
error 200 "Purged.";
}
return (deliver);
}
sub vcl_miss {
if (req.request == "PURGE") {
error 404 "Not in cache.";
}
return (fetch);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment