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

This tutorial will be showing you how to install Matomo web analytics (formerly known as Piwik) on Ubuntu 22.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 22.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. If you are looking for a virtual private server (VPS), I recommend Kamatera VPS, which features:

  • 30 days free trial.
  • Starts at $4/month (1GB RAM)
  • High-performance KVM-based VPS
  • 9 data centers around the world, including United States, Canada, UK, Germany, The Netherlands, Hong Kong, and Isreal.

Follow the tutorial linked below to create your Linux VPS server at Kamatera.

Once you have a VPS running Ubuntu 22.04, 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 22.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 22.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.


Once downloaded, extract the archive with unzip.

sudo apt install unzip

sudo mkdir -p /var/www/

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


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

    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/php8.1-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/php8.1-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 php8.1-mysql php8.1-fpm php8.1-common php8.1-gd php8.1-curl  php8.1-zip php8.1-xml php8.1-mbstring php8.1-bz2 php8.1-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 22.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

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.


Step 6: Finish the Installation in your Web Browser

Go to 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.


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


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


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


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


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


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="//;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= > /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 ''

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:
  • Update the database every week.


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 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 22.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 22.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
    4 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.

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