Search code examples
apache.htaccessnginxbrowser-cachevarnish

Remove a header based on query param with varnish


I want to remove a cache-control header from URL's with a specific query params. e.g. when the query paramater ajax=1 is present.

e.g

www.domain.com?p=3&scroll=1&ajax=1&scroll=1

These are getting cached by chrome browsers for longer than I would like and I would like to stop that in this specific case. I have tried with .htaccess which works for static files however not in action on the URL's mentioned above.

RewriteEngine on
RewriteCond %{QUERY_STRING} (^|&)ajax=1(&|$)
Header unset "Cache-Control"

I could use a cache buster in the next website release but difficult in production and worried it would unnecessarily cache lots of files in user browsers so would rather achieve server side.

My server has Cloudflare then NGINX terminating SSL to Varnish then Apache with a Magento 2 instance running on there. So thinking i could possibly achieve this with NGINX or Varnish configs, or even Cloudflare. I however couldn't seem to find a way to achieve this with page rules in Cloudflare, or could not find examples for Varnish or Nginx.


Solution

  • I'm assuming you don't want to cache when ajax=1 is part of your URL params?

    You can do this in Varnish using the following VCL snippet:

    sub vcl_backend_response {
        if(bereq.url ~ "\?([^&]*&)*ajax=1(&[^&]*)*$") {
            set beresp.http.cache-control = "private, no-cache, no-store";
            set beresp.uncacheable = true;
        } 
    }
    

    This snippet will make sure Varnish doesn't cache responses where the URL contains an ajax=1 URL parameter. It will also make sure any caching proxy that sits in front will not cache, because of the Cache-Control: private, no-cache, no-store.

    Is this what you're looking for?