Skip to content

Instantly share code, notes, and snippets.

@BobbyWibowo
Forked from srstsavage/nginx_google_analytics
Last active October 30, 2023 16:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BobbyWibowo/6d623af59a30a6dab2d4486320f01fa2 to your computer and use it in GitHub Desktop.
Save BobbyWibowo/6d623af59a30a6dab2d4486320f01fa2 to your computer and use it in GitHub Desktop.
google analytics in nginx
server {
listen 80;
server_name yoursite.com;
# 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/yoursite.com.conf;
#
# 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 {
internal;
# don't track internal requests
if ($internal_request) {
return 200;
break;
}
resolver 8.8.8.8 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 "www.google-analytics.com";
proxy_set_header Content-Length "";
proxy_set_header Cookie "";
proxy_set_header Referer "";
set $ga_api "https://www.google-analytics.com";
# DOWNLOAD SIZE TRACKING
# 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;
127.0.0.1 1;
}
# add the lines above somewhere BEFORE your virtual host configs are included
# e.g. BEFORE include /usr/local/nginx/conf/conf.d/*.conf;
}
@BobbyWibowo
Copy link
Author

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