Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
google analytics in nginx
server {
listen 80;
# set $google_analytics_id and include the google_analytics file below
set $google_analytics_id "UA-12345678-9";
include /usr/local/nginx/conf/google-analytics.conf;
location / {
# your normal config goes here...
# call the @ga location as a post_action
post_action @ga;
# send logs for all traffic (including non-html) to google analytics
# in server block:
# set $google_analytics_id "UA-THECORRECT-ID";
# include /usr/local/nginx/conf/conf.d/;
# in location blocks:
# post_action @ga;
userid on;
userid_name cid;
userid_expires 2y;
userid_path "/; Secure; SameSite=None";
set $ga_dp $uri;
set $ga_host $host;
# userid is contained in uid_got or uid_set, depending on if it's already been set
# also the cookie variable name is included (e.g. cid=ASDF), so no need to specify it in the query params
set $cid $uid_got$uid_set;
location @ga {
# don't track internal requests
if ($internal_request) {
return 200;
resolver ipv6=off;
proxy_ignore_client_abort on;
proxy_next_upstream timeout;
proxy_connect_timeout 1s;
proxy_method GET;
proxy_pass_request_headers on;
proxy_pass_request_body off;
proxy_set_header Host "";
proxy_set_header Content-Length "";
proxy_set_header Cookie "";
proxy_set_header Referer "";
set $ga_api "";
# Google Analytics doesn't track download sizes out of the box.
# Here we are using a custom metric (cm1) and sending the value of nginx's bytes_sent
proxy_pass $ga_api/collect?v=1&dp=/$ga_dp&dh=$ga_host&tid=$google_analytics_id&$cid&uip=$remote_addr&t=pageview&cm1=$bytes_sent&dr=$http_referer;
http {
# your normal config goes here
geo $internal_request {
default 0; 1;
# add the lines above somewhere BEFORE your virtual host configs are included
# e.g. BEFORE include /usr/local/nginx/conf/conf.d/*.conf;

This comment has been minimized.

Copy link
Owner Author

@BobbyWibowo BobbyWibowo commented May 25, 2020

We clear out Referer header with proxy_set_header Referer "";, because we will instead pass the value along with &dr=$http_referer.
I don't remember why, but Analytics didn't recognize Referer header with the /collect/ API.

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