使用 Nginx 解決 Google Analytics 无法统计大陆访问数据被墙的问题

由於眾所周之的原因,Google Analytics 在大陸地區總是「不太穩定」,且無其他可真正比肩者。故而需要通過海外服務器作為反向代理以解決此種問題。同時為統計結果之準確計,必須確保用戶IP等信息得以透明傳輸。

解決方案

nginx配置文件:

server {
listen 80;
listen 443 ssl spdy;
server_name analytics.hellomac.com.cn;
ssl_certificate /etc/letsencrypt/live/www.hellomac.com.cn/privkey.pem;
ssl_certificate_key /etc/letsencrypt/live/www.hellomac.com.cn/privkey.pem;
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.hellomac.com.cn/analytics.js','ga');
ga('create', 'UA-EXAMPLE-0', 'auto');
ga('send', 'pageview');

文章出处:https://hacker.design/ji-yu-nginxfan-xiang-dai-li-jie-jue-google/

Related post

  1. NO IMAGE
  2. NO IMAGE
  3. NO IMAGE
  4. NO IMAGE
  5. NO IMAGE
  6. NO IMAGE

    2021.05.23

    Ngrok 搭建指南

There are no comment yet.

ABOUT

老赵的个人博客,关于 Mac, iPhone, iPad, iPod等产品的软件和硬件技术交流。也讨论Linux/UNIX技术,服务器运维技术等。

2025 年 2 月
 1
2345678
9101112131415
16171819202122
232425262728  

Powerd by WordPress on Xserve
Xserve 2009
@2012-2024 HelloMac Copyright