budi budi - 1 month ago 10
Javascript Question

Google Analytics Force HTTPS to Prevent 307 Internal Redirect On Send

When Google Analytics sends data from an http page, it starts out as an http request like so:


But this causes a 307 status code (Internal Redirect) due to HTTP Strict Transport Security (HSTS), and this redirect is the https version of the exact same URL.

How do I force Google to automatically send an https request?


The solution is to use ForceSSL. This forces Google Analytics to always send the data via https.


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

By default, tracking beacons sent from https pages will be sent using https while beacons sent from http pages will be sent using http. Setting forceSSL to true will force http pages to also send all beacons using https.



<!-- Google Analytics -->
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

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

ga.js (legacy)


Configures Google Analytics to send all hits using SSL, even from insecure (HTTP) pages.


Example (async):

<script type="text/javascript">

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

  (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);


Example (traditional .js snippet):

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