Install Matomo Web Analytics (Piwik) on Ubuntu 20.04 with Apache/Nginx

This tutorial will be showing you how to install Matomo web analytics (formerly known as Piwik) on Ubuntu 20.04 with Apache or Nginx web server. Matomo is an open-source alternative to Google Analytics, which is the most widely-used web analytics software.

What’s Web Analytics?

Web analytics software is used by websites to know how many visitors are on a site in a day/week/month, what web browser they are using, etc. It is a crucial piece of software to help grow their websites. Google Analytics is great, but the data of website visitors are stored on Google’s server. If you don’t want to share your website visitors’ data with a third party, you can run your own web analytics software. They are many self-hosted alternatives to Google analytics and Matomo is a great one.

Matomo Features

The open-source (GPL v3+ licensed) self-hosted Matomo edition can show the following reports.

  • Top keywords and search engines, websites, social media websites.
  • Top page URLs, page titles, user countries, providers, operating systems, browser market share, screen resolution, desktop VS mobile.
  • Engagement (time on site, pages per visit, repeated visits).
  • Top campaigns, custom variables, top entry/exit pages, downloaded files, and many more.
  • Classified into four main analytics report categories – Visitors, Actions, Referrers, Goals/Ecommerce (30+ reports).
  • Statistics Email reports.
  • Web server log analytics.
  • Track visitors who have disabled JavaScript.
  • Tools to comply with GDPR (such as cookie consent)
  • Install free or premium plugins to extend and expand the functionality of Matomo.
  • An easy-to-use web-based updater. A command-line updater is also available.
  • And more.

For a full list of features, please check the Matomo features page. I particularly like the fact that Matomo can list all my web pages by page views and show bounce rate and exit rate for each web page, and also the real-time visitor map.

matomo real time visitor map

Matomo Real-Time Visitor Map

Self-hosted Matomo Benefits

  • Full control of data. Data is stored on your server only and you can choose which country the server is located.
  • No data limits. You can hold as much data as your server can.
  • Fully customizable and extensible.
  • Firefox started blocking cross-site tracking cookies, including Google analytics. By hosting the analytics software under your own domain name, your tracking cookies won’t be blocked.

The cloud-hosted Matomo has extra features, but you can install premium plugin on your self-hosted instance to gain the same functionality.

Prerequisites of Installing Matomo Web Analytics (Piwik) on Ubuntu 20.04

To follow this tutorial, you will need a domain name and a server. I registered my domain name at NameCheap because the price is low and they give whois privacy protection free for life. A server with 1G RAM is enough to run Matomo and here are the hosting providers that I recommend. I have used all of them.

  • Vultr (Start at $2.5/month. Credit card required)
  • DigitalOcean (Start at $5/month. No credit card is required. You can use Paypal).

Once you have a server, install Ubuntu on them and follow the instructions below.

Matomo is written in PHP and uses MySQL/MariaDB database. To follow this tutorial, it’s assumed that you have already set up LAMP or LEMP stack on Ubuntu 20.04. If not, please check out one of the following tutorials:

When you are finished setting up LAMP or LEMP stack, come back here and read on.

Step 1: Download Matomo on Ubuntu 20.04

Log in to your server via SSH. You can always use the following command to download the latest version of Matomo on your server.

wget https://builds.matomo.org/matomo-latest.zip

Once downloaded, extract the archive with unzip.

sudo apt install unzip

sudo mkdir -p /var/www/

sudo unzip matomo-latest.zip -d /var/www/

The -d option specifies the target directory. Matomo web files will be extracted to /var/www/matomo/. Then we need to change the owner of this directory to www-data so that the web server can write to this directory.

sudo chown www-data:www-data /var/www/matomo/ -R

Step 2: Create a Database and User in MariaDB

Log into MariaDB database server with the following command.

sudo mysql

Alternatively, you can also use this command to login.

sudo mariadb

Then create a database for Matomo. This tutorial name the database matomo. You can use whatever name you like.

create database matomo;

Create the database user. Again, you can use your preferred name for this user. Replace your-password with your preferred password.

create user matomouser@localhost identified by 'your-password';

Grant this user all privileges on the matomo database.

grant all privileges on matomo.* to matomouser@localhost;

Flush privileges and exit.

flush privileges;

exit;

Step 3: Create Apache or Nginx Configuration File

Apache

If you prefer to use Apache web server, then create a virtual host configuration file in /etc/apache2/sites-available/ directory.

sudo nano /etc/apache2/sites-available/matomo.conf

Put the following text into the file. Replace analytics.example.com with your own domain name. Don’t forget to set A record for the domain name in your DNS manager.

<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        ServerName analytics.example.com
        DocumentRoot /var/www/matomo/

        <Directory /var/www/matomo>
           DirectoryIndex index.php
           Options FollowSymLinks
           AllowOverride All
           Require all granted
        </Directory>

        <Files "console">
           Options None
           Require all denied
        </Files>

        <Directory /var/www/matomo/misc/user>
           Options None
           Require all granted
        </Directory>

        <Directory /var/www/matomo/misc>
           Options None
           Require all denied
        </Directory>

        <Directory /var/www/matomo/vendor>
           Options None
           Require all denied
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/matomo_error.log
        CustomLog ${APACHE_LOG_DIR}/matomo_access.log combined

</VirtualHost>

Save and close the file. Then enable this virtual host.

sudo a2ensite matomo.conf

Reload Apache web server for the change to take effect.

sudo systemctl reload apache2

Nginx

If you prefer to use Nginx web server, then create a matomo.conf file in /etc/nginx/conf.d/ directory.

sudo nano /etc/nginx/conf.d/matomo.conf

Put the following text into the file. Replace analytics.example.com with your own domain name. Don’t forget to set A record for the domain name in your DNS manager.

server {
    listen [::]:80;
    listen 80;
    server_name analytics.example.com;

    access_log /var/log/nginx/matomo.access.log;
    error_log /var/log/nginx/matomo.error.log;

    root /var/www/matomo/; 
    
    index index.php;
        
    ## only allow accessing the following php files
    location ~ ^/(index|matomo|piwik|js/index).php {
        include snippets/fastcgi-php.conf;
        fastcgi_param HTTP_PROXY ""; # prohibit httpoxy: https://httpoxy.org/
        fastcgi_pass unix:/run/php/php7.4-fpm.sock; 
    }
    
    ## needed for HeatmapSessionRecording plugin
    location = /plugins/HeatmapSessionRecording/configs.php { 
        include snippets/fastcgi-php.conf;
        fastcgi_param HTTP_PROXY "";
        fastcgi_pass unix:/run/php/php7.4-fpm.sock; 
    }
    
    ## deny access to all other .php files
    location ~* ^.+\.php$ {
        deny all;
        return 403;
    }

    ## serve all other files normally 
    location / {
        try_files $uri $uri/ =404;
    }
    
    ## disable all access to the following directories 
    location ~ /(config|tmp|core|lang) {
        deny all;
        return 403; # replace with 404 to not show these directories exist
    }
    location ~ /\.ht {
        deny  all;
        return 403;
    }

    location ~ \.(gif|ico|jpg|png|svg|js|css|htm|html|mp3|mp4|wav|ogg|avi|ttf|eot|woff|woff2|json)$ {
        allow all;
        ## Cache images,CSS,JS and webfonts for an hour
        ## Increasing the duration may improve the load-time, but may cause old files to show after an Matomo upgrade
        expires 1h;
        add_header Pragma public;
        add_header Cache-Control "public";
    }

    location ~ /(libs|vendor|plugins|misc/user) {
        deny all;
        return 403;
    }

    ## properly display textfiles in root directory
    location ~/(.*\.md|LEGALNOTICE|LICENSE) {
        default_type text/plain;
    }
}

Save and close the file. Test Nginx configuration, then reload Nginx for the changes to take effect.

sudo nginx -t

sudo systemctl reload nginx

Step 4: Install and Enable PHP Modules

Run the following commands to install PHP modules required or recommended by Matomo.

sudo apt install php-imagick php7.4-mysql php7.4-fpm php7.4-common php7.4-gd php7.4-json php7.4-curl  php7.4-zip php7.4-xml php7.4-mbstring php7.4-bz2 php7.4-intl

If you are using Apache web server, you need to reload it to make it run with these PHP modules.

sudo systemctl reload apache2

Nginx users don’t need to reload.

Now you should be able to visit the Matomo web-based install wizard at http://analytics.example.com, but before entering any information, let’s enable HTTPS.

Step 5: Enable HTTPS

To encrypt the HTTP traffic when you visit the Matomo web interface, we can enable HTTPS by installing a free TLS certificate issued from Let’s Encrypt. Run the following commands to install Let’s Encrypt client (certbot) on Ubuntu 20.04.

sudo apt update
sudo apt install certbot

If you use Nginx, you also need to install the Certbot Nginx plugin.

sudo apt install python3-certbot-nginx

Then run the following command to obtain and install TLS certificate.

sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email [email protected] -d analytics.example.com

If you use Apache, you also need to install the Certbot Apache plugin.

sudo apt install python3-certbot-apache

Then run this command to obtain and install TLS certificate.

sudo certbot --apache --agree-tos --redirect --hsts --staple-ocsp --email [email protected] -d analytics.example.com

Explanation:

  • --nginx: Use the nginx plugin.
  • --apache: Use the Apache plugin.
  • --agree-tos: Agree to terms of service.
  • --redirect: Force HTTPS by 301 redirect.
  • --hsts: Add the Strict-Transport-Security header to every HTTP response. Forcing browser to always use TLS for the domain. Defends against SSL/TLS Stripping.
  • --staple-ocsp: Enables OCSP Stapling. A valid OCSP response is stapled to the certificate that the server offers during TLS.

The certificate should now be obtained and automatically installed.

matomo-install-ubuntu-20.04

Step 6: Finish the Installation in your Web Browser

Go to https://analytics.example.com to launch the web-based install wizard. Then click Next button.

install matomo on ubuntu 20.04 LTS

It will check if your system meets the requirements like PHP extensions. If all requirements are met, then click Next.

matomo-ubuntu-20.04-php-extensions

In the next step, enter the MariaDB username, password and database name your created earlier. You can use the default value in other fields.

matomo-mariadb-database-setup-ubuntu-20.04

After clicking Next, the install wizard will automatically create some tables in the database. Click Next to continue.

matomo-ubuntu-20.04-apache

In the next screen, create an admin user for the Matomo web interface.

matomo-ubuntu-20.04-nginx

After creating the admin user, you need to add a website to collect analytics data.

matomo-analytics-ubuntu-20.04

Then you need to add the JavaScript tracking code to your website.

matomo-installation-ubuntu-20.04

Once that’s done. Click Next button and your Matomo installation is complete. Now you can log into the Matomo dashboard and view visitor data.

matomo dashboard

Track Users with JavaScript Disabled

In the Matomo web interface, click the cog icon on the upper-right corner, then go to websites -> tracking code, and you can choose to track users with JavaScript disabled.

matomo track users with JavaScript enabled

There will be a new tracking code. You need to replace the existing tracking code with the new one. Actually, the new tracking code just adds the following line to the existing tracking code.

<noscript><p><img src="//analytics.example.com/matomo.php?idsite=1&amp;rec=1" style="border:0;" alt="" /></p></noscript>

When a visitor has disabled JavaScript, or when JavaScript cannot be used, the visitor’s browser will download an image.

Set Up Cron Jobs for Medium and High-Traffic Websites

If your website has thousands of page views per day, it’s necessary to set up a cron job to auto-archive Matomo reports. Create the Cron job file with the following command.

sudo nano /etc/cron.d/matomo-archive

Then add the following lines to the file.

MAILTO="[email protected]"
5 * * * * www-data /usr/bin/php /var/www/matomo/console core:archive --url=https://analytics.example.com > /dev/null

Standard output will be sent to /dev/null and standard error will be sent to your email address. Save and close the file. This Cron job will run every hour at 5 minutes past.

How to Set Up Email Notification

If there are more than one user, then it is a good idea to make Matomo be able to send email notification like password reset emails. For how to set up an email server, please check out the following tutorial. Note that I highly recommend running iRedMail mail server on a fresh clean OS. Installing iRedMail on an OS that has other web applications can fail, and likely break existing applications.

If you don’t want to run your own email server, you can set up SMTP relay instead. Please see the following tutorial.

How to Set Up Accurate Geolocation with GeoIP

By default, Matomo guesses visitors’ location based on the language they use. This is not accurate. For example, many non-US visitors choose En-US as the default language for their OS, so there will be more “US visitors” in Matomo report. To get better geolocation, we can use the free MaxMind GeoLite2 IP database.

First, you need to create an account at MaxMind. Maxmind will send you an email. Click the link in the email to set a password, then log in to your MaxMind account.  Next, select My License Key on the left bar.

maxmind license key

Click the Generate New License Key button.

maxmind generate new license key

Give your license key a name, and choose “No” for “Will this key be used for GeoIP Update?” Then click the Confirm button. Your license key will be shown. Note that the license key will be shown only once, so copy it to your clipboard.

matomo maxmind geolocation

Next, click the cog icon (Administration) in Matomo web interface, go to System -> Geolocation. Then download the latest Maxmind GeoIP database to your server. Replace your_license_key with your real license key.

wget -O GeoLite2-City.tar.gz 'https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-City&suffix=tar.gz&license_key=your_license_key'

Extract the tarball.

tar xvf GeoLite2-City.tar.gz

The tarball will be extracted to a directory named like this GeoLite2-City_20200814. Then move the GeoLite2-City.mmdb file to the /var/www/matomo/misc/ directory.

sudo mv GeoLite2-City_20200814/GeoLite2-City.mmdb /var/www/matomo/misc/

Now reload the Matomo Geolocation settings page. Choose the second location provider: GeoIP 2 (Php).

matomo geoip

Click the Save button to save your settings. On the lower part of this page, you can also enter the Download URL so that Matomo can automatically update the GeoIP database.

  • The MaxMind download URL is: https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-City&suffix=tar.gz&license_key=your_license_key
  • Update the database every week.

matomo-analytics-maxmind-geoip-lite-update

Running Matomo Behind Cloudflare CDN

If Matomo is running behind Cloudflare CDN, then Matomo can only see the Cloudflare servers’ IP address. To show the visitors’ real IP address in Nginx, edit the Nginx main configuration file.

sudo nano /etc/nginx/nginx.conf

Add the following directives in http section.

set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 104.16.0.0/12;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 199.27.128.0/21;
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2405:8100::/32;
set_real_ip_from 2c0f:f248::/32;
set_real_ip_from 2a06:98c0::/29;

# use any of the following two
real_ip_header CF-Connecting-IP;
#real_ip_header X-Forwarded-For;

set_real_ip_from defines trusted addresses, in this case Cloudflare IP addresses, that are known to send correct replacement addresses. Save and close the file. Then reload Nginx for the changes to take effect.

sudo systemctl reload nginx

You can check visitors’ IP addresses in Matomo Dashboard -> Visitors -> Visits Log.

You may also want to check Cloudflare’s current IP ranges.

Other Things To Do

That’s it! I hope this tutorial helped you install Matomo on Ubuntu 20.04 server with Apache or Nginx. As always, if you found this post useful, then subscribe to our free newsletter to get more tips and tricks. Take care 🙂

Rate this tutorial
[Total: 2 Average: 5]

4 Responses to “Install Matomo Web Analytics (Piwik) on Ubuntu 20.04 with Apache/Nginx

  • Hello! Thank you for the tutorial.

    Will your instructions for “Running Matomo Behind Cloudflare CDN” work for a Mautic installation as well setup on Ubuntu 20.04 with Nginx and a LEMP stack?

    Thanks!

    • Meaning, instead of Mautic seeing Cloudflare IP’s, will your in instructions here do the same for Mautic — allowing the real visitor IP’s to be viewed (when the website being used is a WordPress site proxied with Cloudflare).

    • Xiao Guoan (Admin)
      3 years ago

      Yes, it will work for all Nginx virtual hosts running on the same server. You don’t need to do it twice.

Leave a Comment

  • Comments with links are moderated by admin before published.
  • Your email address will not be published.
  • Use <pre> ... </pre> HTML tag to quote the output from your terminal/console.
  • Please use the community (https://community.linuxbabe.com) for questions unrelated to this article.
  • I don't have time to answer every question. Making a donation would incentivize me to spend more time answering questions.

The maximum upload file size: 2 MB. You can upload: image. Links to YouTube, Facebook, Twitter and other services inserted in the comment text will be automatically embedded. Drop file here