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

This tutorial will be showing you how to install Matomo web analytics (formerly known as Piwik) on Ubuntu 18.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 are 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 to a third party, you can run your own web analytics. 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 system, browser marketshare, 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 has disabled JavaScript.
  • Tools to comply with GDPR (such as cookie consent)
  • Install free or premium plugins to extend and expand the functionality of Matomo.
  • 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 many data as your server can.
  • Fully customisable and extensible.
  • Firefox started blocking cross-site tracking cookies, including Google analytics. By hosting the analytics software under your own domain name, you 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 18.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 512MB 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 18.04. If not, please check out one of the following tutorial:

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

Step 1: Download Matomo on Ubuntu 18.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. At the time of this writing, the latest version if Matomo 3.7, which comes with a new feature – tag manager. It’s one of the biggest milestones for Matomo in the last few years.


Once downloaded, extract the archive with unzip.

sudo apt install unzip

sudo unzip -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 (Nginx) 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. Since MariaDB is now using unix_socket plugin to authentication user login, there’s no need to enter MariaDB root password. We just need to prefix the mysql command with sudo.

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 identified by 'your-password';

Flush privileges and exit.

flush privileges;


Step 3: Create Apache or Nginx Configuration File


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 the red-colored text with your actual data. Don’t forget to set A record for the domain name.

<VirtualHost *:80>
        ServerAdmin [email protected]
        DocumentRoot /var/www/matomo/

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

        <Files "console">
           Options None
           Require all denied

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

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

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

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


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


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 the red-colored text with your actual data. Don’t forget to set A record for the domain name.

server {
    listen [::]:80; # remove this if you don't want Matomo to be reachable from IPv6
    listen 80;

    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:
        fastcgi_pass unix:/run/php/php7.2-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.2-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.2-mysql php7.2-fpm php7.2-common php7.2-gd php7.2-json php7.2-curl  php7.2-zip php7.2-xml php7.2-mbstring php7.2-bz2 php7.2-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, 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 18.04.

sudo apt install software-properties-common
sudo add-apt-repository ppa:certbot/certbot
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

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


  • --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

Step 6: Finish the Installation in your Web Browser

Go to to launch the web-based install wizard. Then click Next button.

matomo install ubuntu 18.04

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

matomo ubuntu 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

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

matomo ubuntu apache

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

matomo ubuntu nginx

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

matomo analytics ubuntu 18.04

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

matomo installation

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

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= > /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, click the cog icon (Administration) in Matomo, go to System -> Geolocation. Then download the latest Maxmind GeoIP database to your server.


Extract the tarball.

tar xvf GeoLite2-City.tar.gz

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

sudo mv GeoLite2-City_20190226/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.

matomo analytics maxmind geoip lite

Other Things To Do

That’s it! I hope this tutorial helped you install Matomo on Ubuntu 18.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: 3 Average: 4.7]

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

  • Hey, I appreciate your site very much. It’s a frequent resource for me, thank you!

    I have setup Matomo on an additional server, separate from my website. Both are running nginx. Could you provide direction on how to reverse proxy from the primary web server to my Matomo server, with https through Let’s Encrypt?

    If you had a full article on reverse proxy with nginx/Let’s Encrypt you would be a god send haha. I’m always combining and trying new services and I feel like the reverse proxy process is very convoluted. I feel like there is very little reliable documentation out there.

    Thanks again!

  • Thanks for this guide! I tried several others and this one finally helped me.

  • Antonio Huete Jimenez
    2 years ago

    Thank you.

  • Great guide – still working perfectly in July 2020 on a $5/mo Vultr instance. I changed any references to php7.2 to php7.4, and a couple other minor tweaks.

  • alex silva
    1 year ago

    I got this error:

    2021/02/03 22:14:14 [crit] 3618#3618: *67 connect() to unix:/run/php/php7.2-fpm.sock failed (2: No such file or directory) while connecting to upstream, client:, server:, request: "POST / HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.2-fpm.sock:", host: ""

    and it was solved installing php7.2-fpm

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 ( 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