Search code examples
varnishvarnish-vcl

Varnish: Cache Set-Cookie header


I want to cache the set-cookie header for certain specific cookies. The cookies I want to cache are the same for all users and specific to the page. Is that possible with Varnish?


Solution

  • If the cookie is the same for all users, you can override the built-in VCL behavior for Set-Cookie headers in the vcl_backend_response subroutine as follows:

    sub vcl_backend_response {
        if(bereq.url ~ "^/your-page" && beresp.http.Set-Cookie ~ "^yourCookieName=") {
            return(deliver);
        }
    }
    

    I added the yourCookieName check, which you should replace with the name of the actual cookie, to ensure that not every Set-Cookie header would be cached.

    I also added an extra check to ensure the right URL patterns are matched. Please replace the ^/your-page regex pattern with the actual URL pattern or perform an exact string match if you only want to match a single page.