0

I have a lot of websites and want to get analytics from Google about all pages served by the cache.

Is it possible to add javascript or html to the bottom of each page served by the cache?

For example swap </body> with <script>analytics code</script></body>

Yvan
  • 412
  • 4
  • 9
Tyler
  • 77
  • 1
  • 10

3 Answers3

1

You can use mod_ext_filter from apache:

ExtFilterDefine fixtext mode=output intype=text/html cmd="/bin/sed s/</body>/<analytics code></body>/"

<Location />
    # core directive to cause the fixtext filter to
    # be run on output
   SetOutputFilter fixtext
</Location>

For varnish you have ESI. See: Edge Side Includes for more details.

Mircea Vutcovici
  • 17,619
  • 4
  • 56
  • 83
  • I tried this apache filter, it resulted in garbage being displayed on the page. The Edge Side Includes requires changes to the html which we are trying to avoid because there are thousands of sites. – Tyler May 25 '12 at 19:53
0

The short answer is that you can't. Varnish only allows you to edit outbound Headers, not the content of the outbound response. It does allow you to add C code to the vcl file, so you might be able to hack something together, but it's not designed for it.

Otherwise, I would recommend Mircea's options; either using ESI, or modifying apache or whichever webserver you're using to inject the code.

Just in case, as your question didn't make it clear, you don't need to get Varnish to add the Analytics monitoring code in order for the sites to be monitored, only that that code is on the page. The analytics code all works client-side, making calls directly from the visitor's browser.

Make sure to configure varnish to disregard the analytics cookies - your backend webserver doesn't need them, and leaving them will kill your hit rate :)

Kirrus
  • 482
  • 2
  • 11
0

I've written a VMOD to modify response body in varnish before sending it to client. Use it at your own risk https://github.com/aivarsk/libvmod-rewrite

Aivars
  • 11
  • 2