PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Auth checks and varnish

Note: This article was originally published at Planet PHP on 29 October 2011.
Planet PHP

These days everybody seems to be using Varnish to speed up their site. Things are quite simple until you have to do authentication. IIRC it was my co-worker Stefan Paschke who come up with a nice and simply solution to the dilemma that while you may have some content cached in Varnish, you still need to figure out if you can serve the content. The solution is as always by leveraging the HTTP specification. When we need to serve protected content, we simply turn GET requests into HEAD requests, send them to our app and check for HEAD requests inside a listener after the auth checks. In case of a HEAD request we then return the response early and Varnish can check the response to determine if to serve the original GET request or not. The good news is that its all nicely implemented in LiipCacheControlBundle, along with various other tools to better leverage Varnish, ESI and all that good stuff that is well integrated in Symfony2.

You can find the code for the listener on github and here is a varnish config that I ripped out of a project of ours. I hope the config is still sane as I didn't do any tests after cleaning out application specific stuff, but it should be enough to figure out whats happening:

backend default { .host = A"127.0.0.1″; .port = A"81″; } acl purge { A"127.0.0.1″; #localhost for dev purposes } sub vcl_recv { # pipe HEAD requests as we convert all GET requests to HEAD and back later on if (req.request == A"HEADA") { return (pipe); } } sub vcl_hash { } sub vcl_fetch { if (beresp.http.Cache-Control ~ A"(private|no-cache|no-store)A") { return (pass); }if (beresp.status = 200 && beresp.status

It should be noted that in our application we actually create a token which we can authenticated independently of Symfony2, but for now we didn't want to start writing inline C code to add the validation routines into Varnish itself. We might do so later on if we feel we do not have any other places to tweak ..