使用IIS解決Google Analytics在大陸被擋的問題
19 Mar 2017Google Analytics;GA 是分析流量的工具,透過GA所提供Javascript程式碼,嵌入所要分析網站,就可以將訪客的資料傳送至GA server。
在2014年Google服務被大陸封鎖,所以GA在做傳送資料時,在大陸有可能發生網路不穩定的情況,導致有些數據無法收集到。在此透過卡卡網去檢測GA網路回應情況,藉由淘寶網(https://world.taobao.com/)來做比較。根據下圖顯示,GA在某些省分有出現紅色,可能GA有連線不穩定的情況。

原理
如果你是ASP .NET架構的網站,可以藉由IIS的反代理(Reverse Proxy)來解決這個問題。如下圖,有兩個重要的地方。
- 需有個代理的Domain。透過
IIS的Reverse Proxy的功能
,Request 至Google server 擷取analytics.js。 - 傳輸的資料必須做修改。將
analytics.js
裡的內容,將www.google-analytics.com
字串 取代為代理的URL
。

作法
Step1. 下載 http://www.iis.net/extensions/ApplicationRequestRouting 安裝後,IIS管理工具,會出現這兩個功能,如下圖。

Step2. 加入 HTTP_ACCEPT_ENCODING
設定

Step3. 在Web.config加入至
<rewrite>
<rules>
<rule name="Reverse Proxy to analytics" stopProcessing="true">
<match url="(.*)" />
<action type="Rewrite" url="https://www.google-analytics.com/analytics.js" />
<serverVariables><set name="HTTP_ACCEPT_ENCODING" value="false" /></serverVariables>
</rule>
</rules>
<outboundRules>
<rule name="Outbound CDN" preCondition="IsTextContent">
<match filterByTags="None" pattern="www.google-analytics.com" />
<action type="Rewrite" value="www.user.com" />
</rule>
<preConditions>
<preCondition name="IsTextContent">
<add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/(.+)$" />
</preCondition>
</preConditions>
</outboundRules>
</rewrite>
Step4. 在GA提供的Javascript程式碼,須將https://www.google-analytics.com/analytics.js 修改為http://www.user.com(依你Domain決定)。
(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','http://www.user.com','ga');
ga('create', 'UA-xxxxx-1', 'auto');
ga('send', 'pageview');