Nginx 使用 Nginx 解決 Google Analytics 在大陆被牆的問題

cn_boris · 2015年09月19日 · 最后由 TheLover_Z 回复于 2015年09月24日 · 10940 次阅读

需求點

由於眾所周之的原因,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/

没墙 ga 只是墙了 ga admin

#1 楼 @huobazi 墙了吧?我印象中以前用的时候,GA 得到数据,与其它系统(公司买的一个统计数据的服务)得到的数据,好像少了很多很多……

其实最好的办法还是在本地做个 CDN。。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号