LoginSignup
1
1

More than 5 years have passed since last update.

How to set Google Analytics tracking code in Nginx conf

Last updated at Posted at 2018-02-23

Prerequisites

Nginx --with-http_sub_module <- with yum install, nginx comes with this module included.

nginx -V

nginx version: nginx/1.13.9
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-18) (GCC)
built with OpenSSL 1.0.1e-fips 11 Feb 2013
TLS SNI support enabled
configure arguments: --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'
```

How to set

  • create a conf file with sub_filter directive
/etc/nginx/conf.d/analytics.conf
sub_filter '</head>' '<script type="text/javascript">var _gaq = _gaq || [];_gaq.push(["_setAccount", "UA-99999999-9"]);_gaq.push(["_trackPageview"]);(function() {var ga = document.createElement("script"); ga.type = "text/javascript"; ga.async = true;ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ga, s);})();</script></head>';

↑ replace UA-9999999-9 with appropriate UA ID

References

Add Google Analytics tracking code to HTML via nginx
https://gist.github.com/jirutka/5279057

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1