Include Google Analytics Tracking Code in NGINX Server Block

By Digamber Rawat Last updated on
Hello, I am going to teach you how you can include Google Analytics Proxy on Nginx server block. This small tutorial will help you to proxy any particular stylesheet, script and any file from your own domain. Below is the example in which I will proxy Google analytics on NGINX server block.

Proxy Google Analytics With NGINX Server

# Google Analytics Proxy
rewrite ^/ga.js$ /ga/ last;
location /ga/ {
        proxy_pass http://www.google-analytics.com/ga.js;
        break;
}

After that check whether your nginx server block is working fine or not. Hit the below command to check any error.

sudo nginx -t

If your test is passed and not getting any error, then enter the below command to restart the nginx server.

sudo service nginx reload

Given above code rewrites the ga.js filename to the /ga/pseudo-directory. It will allow using the proxy_pass directive to get the file from Google.

By following this process, I will get the full control of the file which is being served.

This method can be used with any file but be aware that every file will increase the extra load on the server. Implementing a caching layer will be an added advantage.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Hire Me