Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ahmadpriatama/a72223775e2189a5e5b62b7d50466517 to your computer and use it in GitHub Desktop.
Save ahmadpriatama/a72223775e2189a5e5b62b7d50466517 to your computer and use it in GitHub Desktop.
runit varnish
#!/bin/bash -e
. ../../bootstrap
PORT=$(basename "$(pwd)"|awk -F- '{print $2}')
BACKEND_PORT=$(basename "$(pwd)"|awk -F- '{print $3}')
TEMP_BASE_DIR=/var/tmp/${USER}-varnish-${PORT}
VARNISH_NAME=$TEMP_BASE_DIR
if [ ! -d "$TEMP_BASE_DIR" ]; then
mkdir -p "$TEMP_BASE_DIR";
chmod og-rwx "$TEMP_BASE_DIR";
fi
cat <<EOF > varnish.conf
vcl 4.0;
backend default {
.host = "127.0.0.1";
.port = "$BACKEND_PORT";
}
# only allow purging of cache from localhost
acl purge {
"127.0.0.1";
}
sub vcl_recv {
# Normalize accept-encoding headers: http://www.varnish-cache.org/docs/trunk/tutorial/vary.html#tutorial-vary
if (req.http.Accept-Encoding) {
if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|tbz|mp3|ogg)\$") {
# No point in compressing these
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 {
# unknown algorithm
unset req.http.Accept-Encoding;
}
}
# Strip non-application cookies from the requests, e.g. cookies set by Google Analytics
if (req.http.cookie) {
# Remove has_js and Google Analytics __* cookies.
set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(__[_a-z]+|has_js)=[^;]*", "");
# Remove a ";" prefix, if present.
set req.http.Cookie = regsub(req.http.Cookie, "^;\s*", "");
if (req.http.cookie ~ "^ *\$") {
unset req.http.cookie;
}
}
# The regex used here matches the standard rails cache buster urls
# e.g. /images/an-image.png?1234567
if (req.method == "GET" && req.url ~ "(-\d+)?\.(css|js|jpg|jpeg|gif|ico|png)\??\d+\$") {
unset req.http.cookie;
}
# Stripping certain params, e.g.
# utm_* - analytics campaign tracking tags
if (req.url ~ "\?") {
set req.url = regsub(req.url, "\?(ref|scp|sq|st|src|utm_[a-z_]+)(\=[^&]*)?", "?");
set req.url = regsuball(req.url, "&(ref|scp|sq|st|src|utm_[a-z_]+)(\=[^&]*)?(?=&|\$)", "");
set req.url = regsub(req.url, "\?&", "?");
set req.url = regsub(req.url, "\?\$", "");
}
if (req.http.Authorization || req.http.Cookie) {
return (pass);
}
if (req.method != "GET" && req.method != "HEAD") {
if (req.method == "PURGE") {
if (!client.ip ~ purge) {
return (synth(405, "Not allowed."));
}
}
return (pass);
}
return (hash);
}
sub vcl_deliver {
if (obj.hits > 0) {
set resp.http.X-Cache = "HIT";
} else {
set resp.http.X-Cache = "MISS";
}
return (deliver);
}
EOF
exec varnishd -a "127.0.0.1:$PORT" -F -f varnish.conf -s "file,$TEMP_BASE_DIR/data,512MB" -n "$VARNISH_NAME" 2>&1 || echo "do you need to create the symlink '$BASE/varnishd?'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment