Reverse proxy Google Tag Manager with Nginx

Reverse proxy Google Tag Manager with Nginx

unblock the function

Just set up the Google Analytics 4 with Google Tag Manager, however, both of them are been blocked by AdBlockers or DNS filters. A self-hosted Ackee helps to record the web traffics, but duplicate the same function with more traffic loads is not worthing. Therefore, I’m trying to reverse proxy the GTM and GA4 with Nginx.

Just a sample configuration here (only works for GA4), comments below to make it better.

set $gtm 'www.googletagmanager.com';
set $ga  'analytics.google.com';

location /gtm.js {
    sub_filter $gtm $server_name;
    sub_filter_types *;
    sub_filter_once off;

    proxy_set_header Accept-Encoding '';
    proxy_pass https://$gtm/gtm.js$is_args$args;
    proxy_redirect off;

    # cache on server
    proxy_cache ZONE0;
    proxy_cache_key $host$uri$is_args$args;
    proxy_cache_valid 200 304 60m;

    # cache in client browser
    expires 1h;
}

location /gtag/js {
    sub_filter $gtm $server_name;
    sub_filter $ga  $server_name;
    sub_filter_types *;
    sub_filter_once off;

    proxy_set_header Accept-Encoding '';

    proxy_pass https://$gtm/gtag/js$is_args$args;
    proxy_redirect off;
    proxy_cache ZONE0;
    proxy_cache_key $host$uri$is_args$args;
    proxy_cache_valid 200 304 60m;

    expires 1h;
}

location /g/collect {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    proxy_pass https://$ga$uri$is_args$args&uip=$remote_addr;
    proxy_redirect off;
    # proxy_cache ZONE0;
    # proxy_cache_key $host$uri$is_args$args;
    # proxy_cache_valid 200 304 60m;
    proxy_cache off;

    expires epoch; # browser no-cache control
}

If you want to reverse proxy the Universal Analytics, see the reference gist: https://gist.github.com/fhferreira/14015373d49b6543601ec5b23f169089.

Although the above snippet have set uip=$remote_addr, the geolocation is still not correct in Google Analytic’s report…

What I’m actually implemented on this site is reverse proxy Baidu Tongji… 😂, much easy than Google’s system.

THE END
Ads by Google

林宏

Frank Lin

Hey, there! This is Frank Lin (@flinhong), one of the 1.41 billion . This 'inDev. Journal' site holds the exploration of my quirky thoughts and random adventures through life. Hope you enjoy reading and perusing my posts.

YOU MAY ALSO LIKE

Using Liquid in Jekyll - Live with Demos

Web Notes

2016.08.20

Using Liquid in Jekyll - Live with Demos

Liquid is a simple template language that Jekyll uses to process pages for your site. With Liquid you can output complex contents without additional plugins.

HTML 相对路径和绝对路径区别分析

Web Notes

2015.09.26

HTML 相对路径和绝对路径区别分析

HTML 初学者会经常遇到这样一个问题,如何正确引用一个文件。比如,怎样在一个 HTML 网页中引用另外一个 HTML 网页作为超链接(hyperlink),怎样在一个网页中插入一张图片。如果你在引用文件时(如加入超链接,或者插入图片等),使用了错误的文件路径,就会导致引用失效(无法浏览链接文件,或无法显示插入的图片等)。

Ads by Google