Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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 <analytics code></body>
share|improve this question
add comment

3 Answers

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.

share|improve this answer
    
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
add comment

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 :)

share|improve this answer
add comment

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.