How to: Not serve cached pages to logged in users using Varnish

How to: Not serve cached pages to logged in users using Varnish

Generally speaking caching is a good thing, it takes a bit load off the web servers and serves the content more quickly to our site visitors. However, there are a few scenarios where caching is not that great: A highly dynamic site for example would not like the new content being published from not being show to clients. Fortunately there is a solution for many of the problems out there: You can purge the cache smartly or simply serve directly (no caching) portions of your site based on different criteria.

Varnish is an HTTP accelerator designed for content-heavy dynamic web sites. In contrast to other web accelerators, such as Squid, which began life as a client-side cache, or Apache and nginx, which are primarily origin servers, Varnish was designed as an HTTP accelerator. Varnish is focused exclusively on HTTP, unlike other proxy servers that often support for FTPSMTP and other network protocols.

There are many solutions out there for caching, from the built in cache in NginX to Varnish which is a very popular reverse proxy. I have already set up purging to work with Varnish so that when new content is published it is served to the site visitors but logged in users were experiencing issues. For example: Varnish would serve a cached page to the visitor instead of a personalize done based on his/her session. So take for example a WordPress site. An administrator might be logged in but on screen you would not be able to see the admin bar and might experience some session issues. The clearest one would be if your site used SSL as Varnish does not support SSL. So now regular HTTP requests are handled by Varnish while your web server handles HTTPS

Varnish offers a few options, some of which are: 1) Create a cache for each user 2) Do not cache logged in users. In my case because there number of users is super small I have no issues serving them content straight from the server. In order to achieve this you need to edit the VCL file used by Varnish and add the following inside sub vcl_fetch:

if (req.http.Cookie ~ “(UserID|_session)”)
      set beresp.http.X-Cacheable = “NO:Got Session”;
For more Varnish rules, check out the following posts:
Enhanced by Zemanta

You may also like...

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: