Google Analytics Proxy with Nginx

Here’s a quick tip! If you need to serve a specific script, stylesheet or any other file from your own domain, you can easily proxy it with nginx. A good example is the ga.js file for Google Analytics. Here’s how I proxy it with nginx, in the server context:

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

This rewrites the ga.js filename to the /ga/ pseudo-directory, in the context of which I can use the proxy_pass directive to fetch the file from Google. This way I have total control over the file that’s being served and especially the HTTP headers, which I was after in the first place.

You can repeat the trick with basically any file, but keep in mind that each one is a little extra load on your server, so add a caching layer where possible.

About the author

Konstantin Kovshenin

WordPress Core Contributor, ex-Automattician, public speaker and consultant, enjoying life in Moscow. I blog about tech, WordPress and DevOps.