How to only track a subdomain with Google Analytics?

google-analytics

Solution

GA will only track the pages where you have placed the code, so it will not track the main domain when the code is only on the subdomain.

There is however the problem that the site on bar.com will be able to access the cookie from all subdomains, which might not be wanted behaviour (the Universal Analytics Cookie does not contain user data, but it contains an anonymous user id). If you want to avoid that you can set your cookie domain (the third parameter to the create call) to match your subdomain.

ga('create', 'UA-XXXXX-Y', 'pages.foo.bar.com');

Or alternative syntac:

ga('create', 'UA-XXXXX-Y', {
  'cookieDomain': 'pages.foo.bar.com',
});

The cookie domain must be the current subdomain or an ancestor of the current (sub-) domain.

Problem

I want to track the traffic of a site hosted in `http://pages.foo.bar.com/~username/`. After creating the property, this is the tracking code I got: ``` <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','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-46830709-2', 'bar.com'); ga('send', 'pageview'); </script> ``` But won't this track all traffic of `bar.com`? On the backend, I only want to visualize the traffic from the site hosted on the folder `~username/`.

Original source