I'm trying to set up Varnish to cache certain static pages on my site for users who have not logged in or added anything to their cart.

Basically, Varnish will check whether the user has any cookies set on the site. If not, it will serve a cached version of the page. This can help dramatically when the page is under heavy load (like during a press push), where the majority of visitors won't have logged in or added anything to the cart.

The problem is, ExpressionEngine and CartThrob both set a bunch of cookies when the user first arrives, before there's any need for session data to be stored. As such, pages are (rightly) never cached by Varnish. I'm seeing these cookies set immediately on the first request:

exp_cartthrob_session_id exp_last_activity exp_last_visit exp_tracker

Ideally, neither EE or CartThrob should set a cookie until either the user logs in or adds something to their cart. Is there any way to prevent all of these cookies from being set on first visit?


1 Answer 1


The answer to this lay in the Varnish configuration. Basically, in the vcl_recv function, I created my logic for whether to "lookup" (check the cache, fetch from the backend if the cache is empty), or "pass" (always serve from the backend).

Then in vcl_pass, I added an HTTP header to the request indicating "this request was passed and should never be cached".

sub vcl_pass {
  set req.http.X-Varnish-Passed = "PASS";
  return (pass);

Finally in vcl_fetch, I checked the HTTP header added to the request. If the header is missing, this request is safe to strip cookies and cache (based on my logic in vcl_recv). If the header is present, we should just serve it from the back end as-is.

sub vcl_fetch {
  if (req.http.X-Varnish-Passed != "PASS") {
    set beresp.ttl = 300s;
    remove beresp.http.set-cookie;
    remove beresp.http.cookie;

This may cause some problems with ExpressionEngine, since it is stripping out cookies on all of my static pages, but the cookies are still set correctly on all uncached pages (product pages, shopping cart, login pages, etc).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.