default.vcl 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. vcl 4.0;
  2. # Based on: https://github.com/mattiasgeniar/varnish-4.0-configuration-templates/blob/master/default.vcl
  3. import std;
  4. import directors;
  5. backend server1 { # Define one backend
  6. .host = "${BACKEND_HOST}"; # IP or Hostname of backend
  7. .port = "${BACKEND_PORT}"; # Port Apache or whatever is listening
  8. .max_connections = 300; # That's it
  9. .probe = {
  10. #.url = "/"; # short easy way (GET /)
  11. # We prefer to only do a HEAD /
  12. .request =
  13. "HEAD / HTTP/1.1"
  14. "Host: ${BACKEND_HOST}"
  15. "Connection: close"
  16. "User-Agent: Varnish Health Probe";
  17. .interval = 5s; # check the health of each backend every 5 seconds
  18. .timeout = 1s; # timing out after 1 second.
  19. .window = 5; # If 3 out of the last 5 polls succeeded the backend is considered healthy, otherwise it will be marked as sick
  20. .threshold = 3;
  21. }
  22. .first_byte_timeout = 300s; # How long to wait before we receive a first byte from our backend?
  23. .connect_timeout = 5s; # How long to wait for a backend connection?
  24. .between_bytes_timeout = 2s; # How long to wait between bytes received from our backend?
  25. }
  26. acl purge {
  27. # ACL we'll use later to allow purges
  28. "localhost";
  29. "127.0.0.1";
  30. "::1";
  31. }
  32. #acl editors {
  33. # # ACL to honor the "Cache-Control: no-cache" header to force a refresh but only from selected IPs
  34. # "localhost";
  35. # "127.0.0.1";
  36. # "::1";
  37. #}
  38. sub vcl_init {
  39. # Called when VCL is loaded, before any requests pass through it.
  40. # Typically used to initialize VMODs.
  41. new vdir = directors.round_robin();
  42. vdir.add_backend(server1);
  43. # vdir.add_backend(servern);
  44. }
  45. sub vcl_recv {
  46. # Called at the beginning of a request, after the complete request has been received and parsed.
  47. # Its purpose is to decide whether or not to serve the request, how to do it, and, if applicable,
  48. # which backend to use.
  49. # also used to modify the request
  50. set req.backend_hint = vdir.backend(); # send all traffic to the vdir director
  51. # Normalize the header, remove the port (in case you're testing this on various TCP ports)
  52. set req.http.Host = regsub(req.http.Host, ":[0-9]+", "");
  53. # Remove the proxy header (see https://httpoxy.org/#mitigate-varnish)
  54. unset req.http.proxy;
  55. # Normalize the query arguments
  56. set req.url = std.querysort(req.url);
  57. # Allow purging
  58. if (req.method == "PURGE") {
  59. if (!client.ip ~ purge) { # purge is the ACL defined at the begining
  60. # Not from an allowed IP? Then die with an error.
  61. return (synth(405, "This IP is not allowed to send PURGE requests."));
  62. }
  63. # If you got this stage (and didn't error out above), purge the cached result
  64. return (purge);
  65. }
  66. # Only deal with "normal" types
  67. if (req.method != "GET" &&
  68. req.method != "HEAD" &&
  69. req.method != "PUT" &&
  70. req.method != "POST" &&
  71. req.method != "TRACE" &&
  72. req.method != "OPTIONS" &&
  73. req.method != "PATCH" &&
  74. req.method != "DELETE") {
  75. # Non-RFC2616 or CONNECT which is weird.
  76. return (pipe);
  77. }
  78. # Implementing websocket support (https://www.varnish-cache.org/docs/4.0/users-guide/vcl-example-websockets.html)
  79. if (req.http.Upgrade ~ "(?i)websocket") {
  80. return (pipe);
  81. }
  82. # Only cache GET or HEAD requests. This makes sure the POST requests are always passed.
  83. if (req.method != "GET" && req.method != "HEAD") {
  84. return (pass);
  85. }
  86. # Some generic URL manipulation, useful for all templates that follow
  87. # First remove the Google Analytics added parameters, useless for our backend
  88. if (req.url ~ "(\?|&)(utm_source|utm_medium|utm_campaign|utm_content|gclid|cx|ie|cof|siteurl)=") {
  89. set req.url = regsuball(req.url, "&(utm_source|utm_medium|utm_campaign|utm_content|gclid|cx|ie|cof|siteurl)=([A-z0-9_\-\.%25]+)", "");
  90. set req.url = regsuball(req.url, "\?(utm_source|utm_medium|utm_campaign|utm_content|gclid|cx|ie|cof|siteurl)=([A-z0-9_\-\.%25]+)", "?");
  91. set req.url = regsub(req.url, "\?&", "?");
  92. set req.url = regsub(req.url, "\?$", "");
  93. }
  94. # Strip hash, server doesn't need it.
  95. if (req.url ~ "\#") {
  96. set req.url = regsub(req.url, "\#.*$", "");
  97. }
  98. # Strip a trailing ? if it exists
  99. if (req.url ~ "\?$") {
  100. set req.url = regsub(req.url, "\?$", "");
  101. }
  102. # Some generic cookie manipulation, useful for all templates that follow
  103. # Remove the "has_js" cookie
  104. set req.http.Cookie = regsuball(req.http.Cookie, "has_js=[^;]+(; )?", "");
  105. # Remove any Google Analytics based cookies
  106. set req.http.Cookie = regsuball(req.http.Cookie, "__utm.=[^;]+(; )?", "");
  107. set req.http.Cookie = regsuball(req.http.Cookie, "_ga=[^;]+(; )?", "");
  108. set req.http.Cookie = regsuball(req.http.Cookie, "_gat=[^;]+(; )?", "");
  109. set req.http.Cookie = regsuball(req.http.Cookie, "utmctr=[^;]+(; )?", "");
  110. set req.http.Cookie = regsuball(req.http.Cookie, "utmcmd.=[^;]+(; )?", "");
  111. set req.http.Cookie = regsuball(req.http.Cookie, "utmccn.=[^;]+(; )?", "");
  112. # Remove DoubleClick offensive cookies
  113. set req.http.Cookie = regsuball(req.http.Cookie, "__gads=[^;]+(; )?", "");
  114. # Remove the Quant Capital cookies (added by some plugin, all __qca)
  115. set req.http.Cookie = regsuball(req.http.Cookie, "__qc.=[^;]+(; )?", "");
  116. # Remove the AddThis cookies
  117. set req.http.Cookie = regsuball(req.http.Cookie, "__atuv.=[^;]+(; )?", "");
  118. # Remove a ";" prefix in the cookie if present
  119. set req.http.Cookie = regsuball(req.http.Cookie, "^;\s*", "");
  120. # Are there cookies left with only spaces or that are empty?
  121. if (req.http.cookie ~ "^\s*$") {
  122. unset req.http.cookie;
  123. }
  124. if (req.http.Cache-Control ~ "(?i)no-cache") {
  125. #if (req.http.Cache-Control ~ "(?i)no-cache" && client.ip ~ editors) { # create the acl editors if you want to restrict the Ctrl-F5
  126. # http://varnish.projects.linpro.no/wiki/VCLExampleEnableForceRefresh
  127. # Ignore requests via proxy caches and badly behaved crawlers
  128. # like msnbot that send no-cache with every request.
  129. if (! (req.http.Via || req.http.User-Agent ~ "(?i)bot" || req.http.X-Purge)) {
  130. #set req.hash_always_miss = true; # Doesn't seems to refresh the object in the cache
  131. return(purge); # Couple this with restart in vcl_purge and X-Purge header to avoid loops
  132. }
  133. }
  134. # Large static files are delivered directly to the end-user without
  135. # waiting for Varnish to fully read the file first.
  136. # Varnish 4 fully supports Streaming, so set do_stream in vcl_backend_response()
  137. if (req.url ~ "^[^?]*\.(7z|avi|bz2|flac|flv|gz|mka|mkv|mov|mp3|mp4|mpeg|mpg|ogg|ogm|opus|rar|tar|tgz|tbz|txz|wav|webm|xz|zip)(\?.*)?$") {
  138. unset req.http.Cookie;
  139. return (hash);
  140. }
  141. # Remove all cookies for static files
  142. # A valid discussion could be held on this line: do you really need to cache static files that don't cause load? Only if you have memory left.
  143. # Sure, there's disk I/O, but chances are your OS will already have these files in their buffers (thus memory).
  144. # Before you blindly enable this, have a read here: https://ma.ttias.be/stop-caching-static-files/
  145. 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|otf|ogg|ogm|opus|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)(\?.*)?$") {
  146. unset req.http.Cookie;
  147. return (hash);
  148. }
  149. # Send Surrogate-Capability headers to announce ESI support to backend
  150. set req.http.Surrogate-Capability = "key=ESI/1.0";
  151. if (req.http.Authorization) {
  152. # Not cacheable by default
  153. return (pass);
  154. }
  155. return (hash);
  156. }
  157. sub vcl_pipe {
  158. # Called upon entering pipe mode.
  159. # In this mode, the request is passed on to the backend, and any further data from both the client
  160. # and backend is passed on unaltered until either end closes the connection. Basically, Varnish will
  161. # degrade into a simple TCP proxy, shuffling bytes back and forth. For a connection in pipe mode,
  162. # no other VCL subroutine will ever get called after vcl_pipe.
  163. # Note that only the first request to the backend will have
  164. # X-Forwarded-For set. If you use X-Forwarded-For and want to
  165. # have it set for all requests, make sure to have:
  166. # set bereq.http.connection = "close";
  167. # here. It is not set by default as it might break some broken web
  168. # applications, like IIS with NTLM authentication.
  169. # set bereq.http.Connection = "Close";
  170. # Implementing websocket support (https://www.varnish-cache.org/docs/4.0/users-guide/vcl-example-websockets.html)
  171. if (req.http.upgrade) {
  172. set bereq.http.upgrade = req.http.upgrade;
  173. }
  174. return (pipe);
  175. }
  176. sub vcl_pass {
  177. # Called upon entering pass mode. In this mode, the request is passed on to the backend, and the
  178. # backend's response is passed on to the client, but is not entered into the cache. Subsequent
  179. # requests submitted over the same client connection are handled normally.
  180. # return (pass);
  181. }
  182. # The data on which the hashing will take place
  183. sub vcl_hash {
  184. # Called after vcl_recv to create a hash value for the request. This is used as a key
  185. # to look up the object in Varnish.
  186. hash_data(req.url);
  187. if (req.http.host) {
  188. hash_data(req.http.host);
  189. } else {
  190. hash_data(server.ip);
  191. }
  192. # hash cookies for requests that have them
  193. if (req.http.Cookie) {
  194. hash_data(req.http.Cookie);
  195. }
  196. }
  197. sub vcl_hit {
  198. # Called when a cache lookup is successful.
  199. if (obj.ttl >= 0s) {
  200. # A pure unadultered hit, deliver it
  201. return (deliver);
  202. }
  203. # https://www.varnish-cache.org/docs/trunk/users-guide/vcl-grace.html
  204. # When several clients are requesting the same page Varnish will send one request to the backend and place the others on hold while fetching one copy from the backend. In some products this is called request coalescing and Varnish does this automatically.
  205. # If you are serving thousands of hits per second the queue of waiting requests can get huge. There are two potential problems - one is a thundering herd problem - suddenly releasing a thousand threads to serve content might send the load sky high. Secondly - nobody likes to wait. To deal with this we can instruct Varnish to keep the objects in cache beyond their TTL and to serve the waiting requests somewhat stale content.
  206. # if (!std.healthy(req.backend_hint) && (obj.ttl + obj.grace > 0s)) {
  207. # return (deliver);
  208. # } else {
  209. # return (fetch);
  210. # }
  211. # We have no fresh fish. Lets look at the stale ones.
  212. if (std.healthy(req.backend_hint)) {
  213. # Backend is healthy. Limit age to 10s.
  214. if (obj.ttl + 10s > 0s) {
  215. #set req.http.grace = "normal(limited)";
  216. return (deliver);
  217. } else {
  218. # No candidate for grace. Fetch a fresh object.
  219. return(miss);
  220. }
  221. } else {
  222. # backend is sick - use full grace
  223. if (obj.ttl + obj.grace > 0s) {
  224. #set req.http.grace = "full";
  225. return (deliver);
  226. } else {
  227. # no graced object.
  228. return (miss);
  229. }
  230. }
  231. # fetch & deliver once we get the result
  232. return (miss); # Dead code, keep as a safeguard
  233. }
  234. sub vcl_miss {
  235. # Called after a cache lookup if the requested document was not found in the cache. Its purpose
  236. # is to decide whether or not to attempt to retrieve the document from the backend, and which
  237. # backend to use.
  238. return (fetch);
  239. }
  240. # Handle the HTTP request coming from our backend
  241. sub vcl_backend_response {
  242. # Called after the response headers has been successfully retrieved from the backend.
  243. # Pause ESI request and remove Surrogate-Control header
  244. if (beresp.http.Surrogate-Control ~ "ESI/1.0") {
  245. unset beresp.http.Surrogate-Control;
  246. set beresp.do_esi = true;
  247. }
  248. # Enable cache for all static files
  249. # The same argument as the static caches from above: monitor your cache size, if you get data nuked out of it, consider giving up the static file cache.
  250. # Before you blindly enable this, have a read here: https://ma.ttias.be/stop-caching-static-files/
  251. 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|otf|ogg|ogm|opus|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)(\?.*)?$") {
  252. unset beresp.http.set-cookie;
  253. }
  254. # Large static files are delivered directly to the end-user without
  255. # waiting for Varnish to fully read the file first.
  256. # Varnish 4 fully supports Streaming, so use streaming here to avoid locking.
  257. if (bereq.url ~ "^[^?]*\.(7z|avi|bz2|flac|flv|gz|mka|mkv|mov|mp3|mp4|mpeg|mpg|ogg|ogm|opus|rar|tar|tgz|tbz|txz|wav|webm|xz|zip)(\?.*)?$") {
  258. unset beresp.http.set-cookie;
  259. set beresp.do_stream = true; # Check memory usage it'll grow in fetch_chunksize blocks (128k by default) if the backend doesn't send a Content-Length header, so only enable it for big objects
  260. }
  261. # Sometimes, a 301 or 302 redirect formed via Apache's mod_rewrite can mess with the HTTP port that is being passed along.
  262. # This often happens with simple rewrite rules in a scenario where Varnish runs on :80 and Apache on :8080 on the same box.
  263. # A redirect can then often redirect the end-user to a URL on :8080, where it should be :80.
  264. # This may need finetuning on your setup.
  265. #
  266. # To prevent accidental replace, we only filter the 301/302 redirects for now.
  267. if (beresp.status == 301 || beresp.status == 302) {
  268. set beresp.http.Location = regsub(beresp.http.Location, ":[0-9]+", "");
  269. }
  270. # Set 2min cache if unset for static files
  271. if (beresp.ttl <= 0s || beresp.http.Set-Cookie || beresp.http.Vary == "*") {
  272. set beresp.ttl = 120s; # Important, you shouldn't rely on this, SET YOUR HEADERS in the backend
  273. set beresp.uncacheable = true;
  274. return (deliver);
  275. }
  276. # Don't cache 50x responses
  277. if (beresp.status == 500 || beresp.status == 502 || beresp.status == 503 || beresp.status == 504) {
  278. return (abandon);
  279. }
  280. # Allow stale content, in case the backend goes down.
  281. # make Varnish keep all objects for 6 hours beyond their TTL
  282. set beresp.grace = 6h;
  283. return (deliver);
  284. }
  285. # The routine when we deliver the HTTP request to the user
  286. # Last chance to modify headers that are sent to the client
  287. sub vcl_deliver {
  288. # Called before a cached object is delivered to the client.
  289. if (obj.hits > 0) { # Add debug header to see if it's a HIT/MISS and the number of hits, disable when not needed
  290. set resp.http.X-Cache = "HIT";
  291. } else {
  292. set resp.http.X-Cache = "MISS";
  293. }
  294. # Please note that obj.hits behaviour changed in 4.0, now it counts per objecthead, not per object
  295. # and obj.hits may not be reset in some cases where bans are in use. See bug 1492 for details.
  296. # So take hits with a grain of salt
  297. set resp.http.X-Cache-Hits = obj.hits;
  298. # Remove some headers: PHP version
  299. unset resp.http.X-Powered-By;
  300. # Remove some headers: Apache version & OS
  301. unset resp.http.Server;
  302. unset resp.http.X-Drupal-Cache;
  303. unset resp.http.X-Varnish;
  304. unset resp.http.Via;
  305. unset resp.http.Link;
  306. unset resp.http.X-Generator;
  307. unset resp.http.X-Debug-Token;
  308. unset resp.http.X-Debug-Token-Link;
  309. set resp.http.Server = "${VARNISH_SERVER}";
  310. set resp.http.X-Powered-By = "MSI<surya.kejawen@gmail.com>";
  311. return (deliver);
  312. }
  313. sub vcl_purge {
  314. # Only handle actual PURGE HTTP methods, everything else is discarded
  315. if (req.method != "PURGE") {
  316. # restart request
  317. set req.http.X-Purge = "Yes";
  318. return(restart);
  319. }
  320. }
  321. sub vcl_synth {
  322. if (resp.status == 720) {
  323. # We use this special error status 720 to force redirects with 301 (permanent) redirects
  324. # To use this, call the following from anywhere in vcl_recv: return (synth(720, "http://host/new.html"));
  325. set resp.http.Location = resp.reason;
  326. set resp.status = 301;
  327. return (deliver);
  328. } elseif (resp.status == 721) {
  329. # And we use error status 721 to force redirects with a 302 (temporary) redirect
  330. # To use this, call the following from anywhere in vcl_recv: return (synth(720, "http://host/new.html"));
  331. set resp.http.Location = resp.reason;
  332. set resp.status = 302;
  333. return (deliver);
  334. }
  335. return (deliver);
  336. }
  337. sub vcl_fini {
  338. # Called when VCL is discarded only after all requests have exited the VCL.
  339. # Typically used to clean up VMODs.
  340. return (ok);
  341. }