Search code examples
phpregexapachevarnishvarnish-vcl

prevent Varnish double cache with N subdomains/normalize host only for varnish


I have a bunch of subdomains that look like:

http://u-c2f86nr3pa.example.org/?s=1
http://u-v1cfu8dsta.example.org/?s=1

Their content is different, but the static files CSS/JS/Favicon are the same. I want to normalize the hostname for them, but I do not want to normalize it for the PHP script as it works based on the subdomain.

Is there a way I can teach varnish that these domains are common, and static should be cached once for them?


Solution

  • You can conditionally rewrite the Host header in the vcl_recv section of your Varnish configuration. You will need a way to identify which URLs are for static content. Here is an example; the specific regular expressions will depend on how your site is structured.

    sub vcl_recv {
        # Normalize Host if URL is one of:
        #     /css/*   /js/*   /favicon*
        if (req.http.Host ~ "^u-\w+\.example\.org$" &&
            req.url ~ "^/(css/|js/|favicon)")
        {
            set req.http.Host = "u-xxxxxxxxx.example.org";
        }
    }
    

    Your backend web server will see the rewritten Host, so make sure you normalize to a name that it recognizes.