During our recent training series, we received a lot of questions concerning how to add the Google Analytics tracking code to a site. Now there are lots of different things to think about before doing this, but a very important and basic one is the security level of your domain. If you have a shopping cart or some kind of secure lead collector, then there’s a good chance that part of your site resides on a secure server, which you may recognize as https:// instead of the normal http://

Why is this important? Because the regular Google Analytics script can cause errors on secure servers, that’s why! Now there are long ways to make sure you don’t run into this problem, and there are easy ways. Well, unless you’re trying to build character or torture yourself (like all of you who aren’t using a separate include for your Google Analytics script), then the easy way is the way to go. Let me share the two easy ways with you…


Easy way #1: Write some code so that you don’t ever have to think about it.

Eh? Basically, you have the code check for the https://. It then inserts the correct version of the urchin.js call, depending on whether the page is secure or not. If you aren’t a coder, feel free to take this code and use it for your own site. Just make sure you enter in your own unique Google Analytics account ID. It’s not really that complicated, so any webmaster worth having will be able to use it.

In JavaScript:
<script type="text/javascript">
if (window.location.protocol == 'https:') {
document.write('<script src="https://ssl.google-analytics.com/urchin.js" type="text/javascript"></sc'+'ript>');
}
else {
document.write('<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></sc'+'ript>');
}
</script>
<script type="text/javascript">
_uacct = "UA-XXXXXX-1";
urchinTracker();
</script>

In PHP:
if($_SERVER['HTTPS'])
{
$google_analytics_url = "https://ssl.google-analytics.com/urchin.js";
}
else
{
$google_analytics_url = "http://www.google-analytics.com/urchin.js";
}
echo "
<script src='$google_analytics_url' type='text/javascript'>
</script>
<script type='text/javascript'>
_uacct = 'XXXXXX-1';
urchinTracker();
</script>
";

You might argue that this doesn’t really look so easy. However, this one code would be all you need on every single page, regardless of whether or not those pages are secure.

Easy way #2: Just use the secure version of the code at all times

Really? Yup. The secure version of the code will work on both secure and non-secure pages:

<script src="https://ssl.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-XXXXX-X";
urchinTracker();
</script>

 

Keep in mind that although either of these solutions will fix any secure page tracking issues you may have been experiencing, it’s not a cure-all for those of you that have the secure part of your site on a separate domain.