Skip to content

Instantly share code, notes, and snippets.

@jirutka
Created March 31, 2013 01:03
Show Gist options
  • Star 36 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save jirutka/5279057 to your computer and use it in GitHub Desktop.
Save jirutka/5279057 to your computer and use it in GitHub Desktop.
Add Google Analytics tracking code to HTML via nginx
#
# Add Google Analytics tracking code to HTML response
#
# Usage:
# set $tracking_id 'UA-12345678-9';
# include incl/analytics.conf;
#
# It needs nginx compiled with option --with-http_sub_module.
# Uses optimized GA code from: http://mathiasbynens.be/notes/async-analytics-snippet
#
sub_filter '</head>' '<script type="text/javascript">var _gaq=[["_setAccount","$tracking_id"],["_trackPageview"]];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;g.src="//www.google-analytics.com/ga.js";s.parentNode.insertBefore(g,s)})(document,"script")</script></head>';
@jacobdr
Copy link

jacobdr commented Jun 23, 2015

Thanks for this. Nice way to inject the tracking code if serving only static files without a template that includes a header and footer on every page.

@kurtabersold
Copy link

Thanks! I changed the javascript to use the newer analytics.js:

sub_filter </head> '<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","$tracking_id","auto");ga("send","pageview");</script></head>';

@zimmertr
Copy link

zimmertr commented Aug 2, 2018

Hi @kurtabersold @jacobdr & @jirutka

How exactly does this work? You compile the open source version of Nginx with this module, and then you add this line to each location block and it will automatically inject the Google Analytics tracking code into the proxied page? Apache, plex, or whatever?

EDIT: I've done so, and nginx starts up cleanly without any errors. But I don't see any data appearing in Google Analytics unfortunately. Is
this a valid example of an http block including the analytics tracking code?

http {
    server  {
        listen  443 ssl;
        server_name www.website.com;
        ssl  on;
        location  / {
            proxy_pass http://12.34.56.78:2000/;

            sub_filter   </head>
                    "<script>
                        <!-- Global site tag (gtag.js) - Google Analytics -->
                        <script async src='https://www.googletagmanager.com/gtag/js?id=UA-##########-1'></script>
                        <script>
                          window.dataLayer = window.dataLayer || [];
                          function gtag(){dataLayer.push(arguments);}
                          gtag('js', new Date());
    
                      gtag('config', 'UA-##########-1');
                    </script>
                </script>";
            sub_filter_once on;
    }
}

EDIT2: I found further information here but am still unable to piece this together.

EDIT3: I did a little digging and learned about the analytics.js file. I've attempted to implement this and also finding it's still not working. Is it necessary to forward ports or anything for this?

http {
    server  {
        listen  443 ssl;
        server_name www.website.com;
        ssl  on;
        location  / {
            proxy_pass http://12.34.56.78:2000/;

            sub_filter </head> '<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-##########","auto");ga("send","pageview");</script></head>';        
            
            sub_filter_once on;
    }
}

EDIT4: I tried calling an entirely separate js file containing the code as well but it still isn't working unfortunately.

http {
    server  {
        listen  443 ssl;
        server_name www.website.com;
        ssl  on;
        location  / {
            proxy_pass http://12.34.56.78:2000/;

            sub_filter  </head>
            '<script language="javascript" src="/etc/nginx/analytics.js"></script></head>';
            sub_filter_once on;
    }
}

The analytics.js file in question:

<!-- 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-##########', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->

@adrfe
Copy link

adrfe commented Oct 12, 2018

Hi @kurtabersold @jacobdr & @jirutka

How exactly does this work? You compile the open source version of Nginx with this module, and then you add this line to each location block and it will automatically inject the Google Analytics tracking code into the proxied page? Apache, plex, or whatever?

EDIT: I've done so, and nginx starts up cleanly without any errors. But I don't see any data appearing in Google Analytics unfortunately. Is
this a valid example of an http block including the analytics tracking code?

http {
    server  {
        listen  443 ssl;
        server_name www.website.com;
        ssl  on;
        location  / {
            proxy_pass http://12.34.56.78:2000/;

            sub_filter   </head>
                    "<script>
                        <!-- Global site tag (gtag.js) - Google Analytics -->
                        <script async src='https://www.googletagmanager.com/gtag/js?id=UA-##########-1'></script>
                        <script>
                          window.dataLayer = window.dataLayer || [];
                          function gtag(){dataLayer.push(arguments);}
                          gtag('js', new Date());
    
                      gtag('config', 'UA-##########-1');
                    </script>
                </script>";
            sub_filter_once on;
    }
}

EDIT2: I found further information here but am still unable to piece this together.

EDIT3: I did a little digging and learned about the analytics.js file. I've attempted to implement this and also finding it's still not working. Is it necessary to forward ports or anything for this?

http {
    server  {
        listen  443 ssl;
        server_name www.website.com;
        ssl  on;
        location  / {
            proxy_pass http://12.34.56.78:2000/;

            sub_filter </head> '<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-##########","auto");ga("send","pageview");</script></head>';        
            
            sub_filter_once on;
    }
}

EDIT4: I tried calling an entirely separate js file containing the code as well but it still isn't working unfortunately.

http {
    server  {
        listen  443 ssl;
        server_name www.website.com;
        ssl  on;
        location  / {
            proxy_pass http://12.34.56.78:2000/;

            sub_filter  </head>
            '<script language="javascript" src="/etc/nginx/analytics.js"></script></head>';
            sub_filter_once on;
    }
}

The analytics.js file in question:

<!-- 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-##########', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->

mkdir -p incl
nano analytics.conf
cd ..
cd conf.d or sites-enabled
go yo your block host
add flowing
include incl/analytics.conf;
set $tracking_id 'UA-12345678-9';
nginx -t
service nginx restart

done

@dandelionred
Copy link

pagespeed module has this as a built-in feature. https://www.modpagespeed.com/doc/filter-insert-ga

pagespeed on;

# This line is optional. Use it if you only want manually enabled filters to be active.
# Details https://www.modpagespeed.com/doc/config_filters
pagespeed RewriteLevel passthrough;

pagespeed EnableFilters insert_ga;
pagespeed AnalyticsID <Analytics ID>;

@iShiBin
Copy link

iShiBin commented May 19, 2020

Hi @kurtabersold @jacobdr & @jirutka

How exactly does this work? You compile the open source version of Nginx with this module, and then you add this line to each location block and it will automatically inject the Google Analytics tracking code into the proxied page? Apache, plex, or whatever?

EDIT: I've done so, and nginx starts up cleanly without any errors. But I don't see any data appearing in Google Analytics unfortunately. Is
this a valid example of an http block including the analytics tracking code?

http {
    server  {
        listen  443 ssl;
        server_name www.website.com;
        ssl  on;
        location  / {
            proxy_pass http://12.34.56.78:2000/;

            sub_filter   </head>
                    "<script>
                        <!-- Global site tag (gtag.js) - Google Analytics -->
                        <script async src='https://www.googletagmanager.com/gtag/js?id=UA-##########-1'></script>
                        <script>
                          window.dataLayer = window.dataLayer || [];
                          function gtag(){dataLayer.push(arguments);}
                          gtag('js', new Date());
    
                      gtag('config', 'UA-##########-1');
                    </script>
                </script>";
            sub_filter_once on;
    }
}

EDIT2: I found further information here but am still unable to piece this together.

EDIT3: I did a little digging and learned about the analytics.js file. I've attempted to implement this and also finding it's still not working. Is it necessary to forward ports or anything for this?

http {
    server  {
        listen  443 ssl;
        server_name www.website.com;
        ssl  on;
        location  / {
            proxy_pass http://12.34.56.78:2000/;

            sub_filter </head> '<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-##########","auto");ga("send","pageview");</script></head>';        
            
            sub_filter_once on;
    }
}

EDIT4: I tried calling an entirely separate js file containing the code as well but it still isn't working unfortunately.

http {
    server  {
        listen  443 ssl;
        server_name www.website.com;
        ssl  on;
        location  / {
            proxy_pass http://12.34.56.78:2000/;

            sub_filter  </head>
            '<script language="javascript" src="/etc/nginx/analytics.js"></script></head>';
            sub_filter_once on;
    }
}

The analytics.js file in question:

<!-- 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-##########', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->

Hi, did you get any luck to make it work?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment