由於眾所周之的原因,Google Analytics 在大陸地區總是「不太穩定」,且無其他可真正比肩者。故而需要通過海外服務器作為反向代理以解決此種問題。同時為統計結果之準確計,必須確保用戶 IP 等信息得以透明傳輸。
nginx 配置文件:
server {
listen 80;
listen 443 ssl spdy;
server_name analytics.example.com;
ssl_certificate /usr/local/tengine/certs/example.crt;
ssl_certificate_key /usr/local/tengine/certs/example.key;
location /ga_proxy {
proxy_set_header X-real-ip $remote_addr;
rewrite ^/ga_proxy/(.*)$ /$1?$args&uip=$remote_addr;
proxy_pass http://www.google-analytics.com;
break;
}
location /analytics.js {
default_type text/html;
subs_filter_types text/css text/xml text/javascript;
subs_filter 'www.google-analytics.com' 'analytics.example.com/ga_proxy' g;
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Referer https://www.google-analytics.com;
proxy_set_header Host www.google-analytics.com;
proxy_pass https://www.google-analytics.com;
proxy_set_header Accept-Encoding "";
}
}
客戶端 JS 代碼:
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//analytics.example.com/analytics.js','ga');
ga('create', 'UA-EXAMPLE-0', 'auto');
ga('send', 'pageview');
原文首發於我的博客 https://hacker.design/ji-yu-nginxfan-xiang-dai-li-jie-jue-google/