Traducciones al Español
Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.
Create a Linode account to try this guide with a $ credit.
This credit will be applied to any valid services used during your first  days.

Google Analytics offers detailed statistics related to visitor traffic and sales for your website, allowing you to better know your audience. It can be beneficial to any website owner interested in growing their visitor base.

Although Google Analytics provides a way to add the tracking code to your webpages, if you are not using PHP includes, Server Side Includes, or another form of layout template, the process can be tedious and inefficient. This guide provides two alternatives to inserting the Google Analytics tracking code to your website, depending on your website’s set-up.

Note

The steps in this guide require root privileges. Be sure to run the steps below as root or with the sudo prefix. For more information on privileges see our Users and Groups guide.

This guide also assumes you have configured your Apache server as described in our LAMP guides with your publicly accessible directory located at something similar to /var/www/example.com/public_html. Replace all instances of example.com with your own domain information.

Signing Up for Google Analytics

Prior to adding Google Analytics to your website, you need to sign up and set up your Google Analytics account.

  1. Navigate to the Google Analytics website, clicking the Access Google Analytics button to the top right.

  2. Click Sign Up.

  3. Be sure the Website option is selected, then enter your account information as desired. Be sure that your website URL is accurate.

    Google Analytics account creation

  4. Press Get Tracking ID, and read through and accept the Google Analytics Terms of Service.

  5. You will then be given your Tracking ID and tracking code. Make note of both of these items, you will use them later.

You can now add this code to your website through PHP, or an external JavaScript file.

Add Through PHP

If your website is coded using PHP (your files will end in .php), you can add the tracking code through a PHP script. This is useful if you are not using a separate PHP file for your header, or otherwise want to keep the code itself outside of your header file. This also makes any additional changes to the tracking code far more efficient, since you will only have to edit one file.

  1. Navigate to the directory your website is hosted in:

    cd /var/www/example.com/public_html
    
  2. Create a file named googleanalytics.php and copy your tracking code:

    File: /var/www/example.com/public_html/googleanalytics.php
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    
    <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-00000000-0', 'auto');
     ga('send', 'pageview');
    
    </script>
    Note

    If you copy the above code, replace UA-00000000-0 with your tracking ID.

    At this time you may want to consider enabling the demographics feature of Google Analytics. If you decide to do so, you will need to add an additional line of code to your JavaScript in the steps below. Insert the following between the lines containing ga('create', 'UA-00000000-0', 'auto'); and ga('send', 'pageview');:

    ga('require', 'displayfeatures');
    

    Should you decide to disable the demographics feature at a later date, simply remove the above code.

  3. If your website does not have a separate header file, and you need to insert the code in every page, skip to step 6; otherwise, open and add the following code to your header document (header.php here) after your <body> tag:

    File: /var/www/example.com/public_html/header.php
    1
    
    <?php include_once("googleanalytics.php") ?>

    You have now added Google Analytics to your website! It may take up to twenty-four hours for any data concerning your website to show up on Google Analytics. You need not follow the rest of this guide.

  4. If your PHP-enabled website does not have a header template, then you can insert the needed code to your website through the terminal. Make sure you are in the directory that holds your website’s files.

    Through using the stream editor command (sed), you can insert the needed code into multiple documents at once:

    sed -i 's/<body>/<body><?php include_once("googleanalytics.php") ?>/g' *.php
    
    Note
    If the <body> tag of your website contains other variables, please adjust the two instances of <body> in the above code to match your current coding.
  5. To see if the code was successfully inserted into your website’s files, you can either open your website in your browser and view the source file, or open up a file in the terminal. When you view the file, you should see the code inserted immediately after the <body> tag:

    File: /var/www/example.com/public_html/index.php
    1
    
    <body><?php include_once("googleanalytics.php") ?>

You have now added Google Analytics to your website! It may take up to twenty-four hours for any data concerning your website to show up on Google Analytics.

Add Through External JavaScript

If your website cannot use PHP (its files end in .html, .htm, or otherwise), you can insert the Google Analytics code through your terminal, using an external JavaScript file and the sed command.

  1. Navigate to the directory your website is hosted in:

    cd /var/www/example.com/public_html
    
  2. (Optional) If you already have a JavaScript folder, change directories to that folder. Otherwise, create a JavaScript folder now:

     mkdir javascript
    

    Navigate to your newly-made folder:

     cd javascript
    
  3. Create a ga.js file to hold your Google Analytics code. Insert the following code, replacing UA-00000000-0 with your tracking ID:

    File: /var/www/example.com/public_html/javascript/ga.js
    1
    2
    3
    4
    5
    6
    7
    
    (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-00000000-0', 'auto');
    ga('send', 'pageview');
    Note

    At this time you may want to consider enabling the demographics feature of Google Analytics. If you decide to do so, you will need to add an additional line of code to your JavaScript in the steps below. Insert the following between the lines containing ga('create', 'UA-00000000-0', 'auto'); and ga('send', 'pageview');:

    ga('require', 'displayfeatures');
    

    Should you decide to disable the demographics feature at a later date, simply remove the above code.

  4. Use the sed command to insert a link to the JavaScript file holding your tracking code. Sed which will search for and replace all instances of your <head> tag with <head><script type="text/javascript" src="javascript/ga.js"></script>:

    sed -i 's@<head>@<head><script type="text/javascript" src="javascript/ga.js"></script>@g' *.html
    
    Note
    Change the .html ending to match the ending of your website’s files.
  5. To check that the code has been successfully inserted into your .html files, you can either open up your website in your browser and view the source code, or view a file in your terminal. The following should appear in conjunction to your <head> tag:

    File: /var/www/example.com/public_html/index.html
    1
    
    <head><script type="text/javascript" src="javascript/ga.js"></script>

    You have now added Google Analytics to your website! It may take up to twenty-four hours for any data concerning your website to show up on Google Analytics.

More Information

You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

This page was originally published on


Your Feedback Is Important

Let us know if this guide was helpful to you.


Join the conversation.
Read other comments or post your own below. Comments must be respectful, constructive, and relevant to the topic of the guide. Do not post external links or advertisements. Before posting, consider if your comment would be better addressed by contacting our Support team or asking on our Community Site.
The Disqus commenting system for Linode Docs requires the acceptance of Functional Cookies, which allow us to analyze site usage so we can measure and improve performance. To view and create comments for this article, please update your Cookie Preferences on this website and refresh this web page. Please note: You must have JavaScript enabled in your browser.