Search code examples
varnishvarnish-vcl

Redirect all png requests as jpg requests in Varnish


I want to redirect all .png requests to .jpg requests in Varnish VCL Example: http://example.com/images/boy.png (or .PNG) to http://example.com/images/boy.jpg in Varnish VCL


Solution

  • There can be 2 cases.

    A. Client redirection [1], use this in case you want to tell client's browser that the image has been moved:

    sub vcl_recv {
      # ...
      if (req.url ~ "(?i)\.png$") {
        error 750 "http://" + req.host + regsub(req.url, "(?i)\.png$", ".jpg$");
      }
      # ...
    }
    
    sub vcl_error {
      # ...
      if (obj.status == 750) {
        set obj.http.Location = obj.response;
        set obj.status = 302;
        return(deliver);
      }
      # ...
    }
    

    B. Server side rewrite [2], use this in case you want to internally change the request without telling the client:

    sub vcl_recv {
      # ...
      if (req.url ~ "(?i)\.png$") {
        set req.url = regsub(req.url, "(?i)\.png$", ".jpg$");
      }
      # ...
    }
    

    PD: Please don't duplicate your questions

    [1] https://www.varnish-cache.org/trac/wiki/VCLExampleRedirectInVCL

    [2] https://www.varnish-cache.org/trac/wiki/RedirectsAndRewrites