Google Analytics强制使用HTTPS来阻止307内部重定向

时间:2016-06-13 21:39:44

标签: javascript google-analytics measurement-protocol

当Google Analytics从http页面发送数据时,它会像http请求一样开始:

http://www.google-analytics.com/collect?payload-data-goes-here

但由于HTTP Strict Transport Security (HSTS),这会导致307状态代码(内部重定向),而此重定向是完全相同网址的https版本。

如何强制Google Analytics仅从http页面发送一个https请求?

1 个答案:

答案 0 :(得分:9)

解决方案是使用ForceSSL。这会迫使Google Analytics 始终通过https发送数据。

<强>的analytics.js

ga('set', 'forceSSL', true);
  

默认情况下,从https页面发送的跟踪信标将使用https发送,而从http页面发送的信标将使用http发送。将forceSSL设置为true将强制http页面也使用https发送所有信标。

https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#forceSSL

示例:

<!-- Google Analytics -->
<script>
(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','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXX-Y', 'auto');
ga('set', 'forceSSL', true); // <---------------------------- add this!
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->

ga.js(遗产)

_gaq.push(['_gat._forceSSL']);
  

将Google Analytics配置为使用SSL发送所有匹配,即使是从不安全的(HTTP)页面发送也是如此。

https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApi_gat#_forcessl

示例(异步):

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-X']);
  _gaq.push(['_gat._forceSSL']); // <------------------------ add this!
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

示例(传统.js代码段):

var pageTracker = _gat._getTracker("UA-XXXXX-X");
_gat._forceSSL(); // <---------------------------------------- add this!
pageTracker._trackPageview();