Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Google Analytics Proxy
location = /analytics.js {
proxy_hide_header Alt-Svc;
resolver 8.8.8.8 ipv6=off;
proxy_pass https://www.google-analytics.com/analytics.js;
break;
}
location = /analytics {
access_by_lua_block {
ngx.req.read_body()
local body = ngx.req.get_body_data()
local uip = ngx.var.remote_addr
local h = ngx.req.get_headers()
local ua = h["User-Agent"]
if (ua == nil) then
ua = "unset"
end
ngx.req.set_body_data(body .. "&uip=" .. uip .. "&ua=" .. ua)
}
proxy_hide_header Alt-Svc;
resolver 8.8.8.8 ipv6=off;
proxy_pass https://www.google-analytics.com/collect;
break;
}
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','" . "/analytics.js','ga');
ga('create', 'UA-xxxxxx-x', 'domain.com');
ga(function(u) {u.set('sendHitTask', function(model) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/analytics', true);
xhr.send(model.get('hitPayload'));
});});
ga('send', 'pageview');

This is cool. Is it possible to achieve this without access_by_lua_block or needing the Lua module

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment