5

If I want my varnish cache server to replace content inside a page (ie: change the class on a div) from the backend before serving or storing the page (vcl_fetch?), how can this be done?

I would like to use simple regex to perform the replacement as I imagine it is supported natively in varnish.

tweak2
  • 646
  • 5
  • 15

1 Answers1

6

Modifying response body is not natively supported by Varnish. You need a Varnish module (vmod) for this.

Aivars Kalvans has libvmod-rewrite, which does exactly what you are looking for. However the vmod is a proof of concept and according to Aivars it is not ready for production use. You can use it as a starting point in any case.

If you are using Apache, you can use mod_ext_filter to modify response body. Here's an example from mod_ext_filters documentation. Since you can pass the response body to any external command, it is very easy to do the necessary modifications to the content.

# mod_ext_filter directive to define a filter which
# replaces text in the response
#
ExtFilterDefine fixtext mode=output intype=text/html cmd="/bin/sed s/verdana/arial/g"

<Location />
# core directive to cause the fixtext filter to
# be run on output
SetOutputFilter fixtext
</Location> 
Ketola
  • 2,767
  • 18
  • 21
  • Ended up just writing my own passthrough before it gets to varnish. I'll have a look at libvmod-rewrite though. Thanks. – tweak2 Apr 15 '13 at 18:53
  • Regarding `mod_ext_filters` I think maybe [mod_substitute](http://httpd.apache.org/docs/2.4/mod/mod_substitute.html) might be an even better fit for the usecase, if apache is an option – George Feb 08 '17 at 19:53