How to Install Matomo with Nginx on Ubuntu

Matomo is a self-hosted web analytics platform that gives you complete ownership of your visitor data. Unlike cloud-based analytics services, Matomo runs entirely on your own server, which means your analytics data never leaves your infrastructure. As a result, it is ideal for organizations with strict privacy requirements, GDPR compliance needs, or anyone who wants full control over their website metrics without relying on third-party services.

By the end of this guide, you will have a fully functional Matomo installation running on a LEMP stack (Linux, Nginx, MariaDB, PHP) with SSL encryption via Let’s Encrypt. Once complete, you will be able to track page views, user behavior, conversions, and e-commerce metrics across multiple websites from a single dashboard.

This guide covers Ubuntu 22.04 LTS, 24.04 LTS, and 26.04 LTS installations. Because the default PHP version differs between releases (PHP 8.1 on 22.04, PHP 8.3 on 24.04, and PHP 8.4 on 26.04), follow the version-specific notes where indicated. Commands are otherwise identical across all supported LTS releases.

Install Nginx

Update Ubuntu Before Matomo Installation

First, update your system to ensure a smooth Matomo installation on Ubuntu. This step is crucial to prevent conflicts during the installation, since Matomo is a complex application that relies on multiple server components.

Execute the command below in your terminal to update your system:

sudo apt update && sudo apt upgrade

Put simply, the first part refreshes your package list, while the second part upgrades installed packages to their latest versions.

Install Essential Packages for Matomo

Before proceeding with the Matomo installation, install the necessary packages with the following command:

sudo apt install curl git wget unzip zip

Specifically, these utilities handle downloading, version control, and archive extraction during installation and updates.

Install Nginx via APT Command

With the dependencies in place, begin building your LEMP stack by installing Nginx:

sudo apt install nginx

After installation, verify that Nginx is running correctly:

systemctl status nginx

If successful, the output will show active (running):

● nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: enabled)
     Active: active (running) since ...
   Main PID: 1234 (nginx)
...

If Nginx is not active, you can enable and start it with this command:

sudo systemctl enable nginx --now

Install Nginx Mainline for Enhanced Performance

For optimal Matomo performance, you may want to consider installing the latest Nginx mainline version instead. This version provides advanced features and improvements for better speed and performance.

Follow the guide to install Nginx Mainline on Ubuntu LTS: Install Nginx Mainline on Ubuntu.

Configure UFW for Nginx and Matomo

Understanding UFW Profiles for Nginx

Before configuring specific rules, it is essential to understand the available UFW profiles for Nginx. Each profile serves different requirements:

  • Nginx HTTP: This profile opens port 80, which is used for standard, unencrypted web traffic.
  • Nginx HTTPS: Opens port 443, used for secure, encrypted traffic.
  • Nginx Full: Combines HTTP and HTTPS profiles, opening ports 80 and 443.

To bring up the profile list, use the following command:

sudo ufw app list

Then, specify which profile you want to use. For most Matomo installations, select ‘Nginx Full’ to allow both HTTP and HTTPS traffic:

sudo ufw allow 'Nginx Full'

When successful, the output confirms the rule was added:

Rule added
Rule added (v6)

Customizing UFW Rules

Beyond the standard profiles, UFW also allows for more granular control. Here are some additional examples:

Block Specific IP Addresses

For enhanced security, you can block incoming traffic from specific IP addresses:

sudo ufw deny from 192.168.1.100

For example, this command blocks all incoming traffic from the IP address 192.168.1.100. Simply replace this with any IP address you want to block.

Deleting Rules

If you need to delete a rule, first list all rules with their numbers:

sudo ufw status numbered

As a result, the output displays each rule with a number you can reference:

Status: active

     To                         Action      From
     --                         ------      ----
[ 1] Nginx Full                 ALLOW IN    Anywhere
[ 2] 22/tcp                     ALLOW IN    Anywhere
[ 3] Nginx Full (v6)            ALLOW IN    Anywhere (v6)
[ 4] 22/tcp (v6)                ALLOW IN    Anywhere (v6)

To delete a specific rule, reference its number. For example, to remove rule 2:

sudo ufw delete 2

More information can be found on UFW to secure your server and Matomo instance in our guide on installing UFW on Ubuntu.

Install MariaDB

Installing MariaDB for Matomo

MariaDB is a preferred database for the LEMP stack because it offers enhanced performance over MySQL. If you require specific versions of MariaDB, such as 11.x or 10.x, refer to the detailed guide for optimal results on Ubuntu: Install MariaDB on Ubuntu.

To install MariaDB, run the following command:

sudo apt install mariadb-server mariadb-client

Verifying MariaDB Service Status

Once installation completes, verify that MariaDB is running properly:

systemctl status mariadb

If successful, the output will show active (running):

● mariadb.service - MariaDB database server
     Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; preset: enabled)
     Active: active (running) since ...
   Main PID: 1234 (mariadbd)
...

Note that the MariaDB version varies by Ubuntu release: 10.6 on Ubuntu 22.04, 10.11 on Ubuntu 24.04, and 11.8 on Ubuntu 26.04. However, all versions are compatible with Matomo.

However, if MariaDB is not active, enable and start the service using:

sudo systemctl enable mariadb --now

Secure MariaDB with Security Script

Securing your MariaDB installation is vital for data integrity and protection against unauthorized access. Since default settings in new installations might be vulnerable, the mysql_secure_installation script significantly enhances security.

Initiate the security configuration process with this command:

sudo mysql_secure_installation

During this process, the script prompts you with several security questions. For a production server, answer Y (yes) to all prompts:

  • Switch to unix_socket authentication: Y (recommended for local access)
  • Change the root password: Y (set a strong password)
  • Remove anonymous users: Y (prevents unauthorized access)
  • Disallow root login remotely: Y (root should only connect locally)
  • Remove test database: Y (removes the insecure test database)
  • Reload privilege tables: Y (applies changes immediately)

Once complete, you will see the message “All done! … your MariaDB installation should now be secure.”

Install PHP

Installing PHP for Matomo

PHP is essential for the LEMP stack because it bridges Nginx and MariaDB. Additionally, it processes the dynamic content for Matomo. For specific PHP versions tailored to different needs, refer to our guide on installing PHP on Ubuntu.

Now install PHP along with PHP-FPM and the modules required by Matomo. The package list below includes all extensions from Matomo’s official requirements:

sudo apt install php php-fpm php-mbstring php-bcmath php-xml php-mysql php-common php-gd php-cli php-curl php-zip php-imagick php-ldap php-intl

As a result, this command installs PHP-FPM for Nginx integration, along with extensions for multibyte strings, database connectivity, image processing, and internationalization.

Verify PHP-FPM Service Status

Once installation completes, verify that PHP-FPM is running. First, check your installed PHP version to determine the correct service name:

php --version

When complete, the output shows your PHP version. Use the major and minor version number (e.g., 8.1, 8.3, or 8.4) in the service status command. For each Ubuntu LTS release, the default PHP-FPM service name is:

  • Ubuntu 22.04 LTS: php8.1-fpm
  • Ubuntu 24.04 LTS: php8.3-fpm
  • Ubuntu 26.04 LTS: php8.4-fpm

Then check the service status using your version. For example, on Ubuntu 24.04:

systemctl status php8.3-fpm

If successful, the output will show active (running):

● php8.3-fpm.service - The PHP 8.3 FastCGI Process Manager
     Loaded: loaded (/usr/lib/systemd/system/php8.3-fpm.service; enabled; preset: enabled)
     Active: active (running) since ...
   Main PID: 1234 (php-fpm8.3)
...

Be sure to note your PHP version, as you will need it when configuring the Nginx server block later in this guide.

Configure Matomo Backend

Downloading and Setting Up Matomo

Downloading Matomo

To begin, download the latest Matomo release using wget. This command fetches the .tar.gz file from Matomo’s official source:

wget https://builds.matomo.org/matomo-latest.tar.gz

Preparing the Matomo Directory

Next, create a dedicated directory for Matomo before extraction. This step organizes your installation:

sudo mkdir -p /var/www/html/matomo

Extracting the Matomo Archive

After that, extract the downloaded .tar.gz file into the Matomo directory. In particular, the tar command handles extraction and ensures the files land in the correct location:

sudo tar -xzf matomo-latest.tar.gz -C /var/www/html/matomo --strip-components=1

Here, the --strip-components=1 flag removes the top-level directory from the archive, placing the contents directly into the Matomo directory.

To confirm the extraction was successful, list the directory contents:

ls /var/www/html/matomo

If successful, a directory listing shows the Matomo directory structure:

config  console  core  CREDITS.md  js  lang  libs  LICENSE  matomo.js  misc  plugins  piwik.js  piwik.php  robots.txt  tmp  vendor

Configuring File Permissions for Matomo

Proper file permissions are essential for Matomo’s security and correct functioning.

Directories Permissions

First, set the permissions for directories to allow adequate access:

sudo find /var/www/html/matomo -type d -exec chmod 755 {} \;

In effect, this command sets directory permissions to 755, which is the standard for web directories.

Files Permissions

Next, apply the correct permissions to files:

sudo find /var/www/html/matomo -type f -exec chmod 644 {} \;

By setting files to 644, you permit reading and writing by the owner, while providing read-only access for others. This balances security with functionality.

Set File Ownership

Since Nginx and PHP-FPM run as the www-data user, you must transfer ownership of the Matomo files so the web server can read, write, and execute files as needed:

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

Importantly, this step is critical. Without proper ownership, Matomo cannot create temporary files, write configuration data, or process updates.

Configuring Nginx for Matomo

Create a dedicated server block to serve your Matomo application. The configuration below is based on Matomo’s official Nginx configuration repository, adapted for Ubuntu’s directory structure:

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

Create the Server Block Configuration

Add the following configuration to the file. Be sure to replace matomo.example.com with your actual domain name:

Note that the configuration below uses php8.3-fpm.sock for Ubuntu 24.04. Adjust the socket path to match your PHP version: php8.1-fpm.sock for Ubuntu 22.04 or php8.4-fpm.sock for Ubuntu 26.04. You can verify your PHP version with php --version.

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

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

    root /var/www/html/matomo;
    index index.php;
    
    location ~ ^/(index|matomo|piwik|js/index).php {
        include snippets/fastcgi-php.conf;
        fastcgi_param HTTP_PROXY "";
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
    }
    
    location = /plugins/HeatmapSessionRecording/configs.php { 
        include snippets/fastcgi-php.conf;
        fastcgi_param HTTP_PROXY "";
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
    }
    
    location ~* ^.+\.php$ {
        deny all;
        return 403;
    }

    location / {
        try_files $uri $uri/ =404;
    }
    
    location ~ /(config|tmp|core|lang) {
        deny all;
        return 403;
    }
    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;
        expires 1h;
        add_header Pragma public;
        add_header Cache-Control "public";
    }

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

    location ~/(.*\.md|LEGALNOTICE|LICENSE) {
        default_type text/plain;
    }
}

Breaking Down the Nginx Configuration for Matomo

Overall, the Nginx configuration file for Matomo is structured to ensure optimal performance and security. Below is a detailed breakdown of its key components:

  • HTTP Listening: Using the listen directives, Nginx is configured to listen on port 80 for both IPv4 and IPv6. This setup is crucial for handling web traffic.
  • Server Name: By setting the server_name directive, you specify the domain name for the Matomo instance, which is essential for directing requests to the correct server block.
  • Logging: With the access_log and error_log directives, you define paths for storing access and error logs, respectively. These logs are vital for monitoring and troubleshooting.
  • Document Root and Index File: The root directive sets the root directory where Matomo files are located, while the index directive specifies that index.php should be the default file to serve.
  • PHP File Processing:
    • Specific PHP Files: Within the location ~ ^/(index|matomo|piwik|js/index).php block, settings for processing main PHP files of Matomo are defined. This block also prevents the httpoxy vulnerability using fastcgi_param HTTP_PROXY "";.
    • Heatmap Plugin: For the HeatmapSessionRecording plugin, the location = /plugins/HeatmapSessionRecording/configs.php block ensures it functions correctly.
    • PHP-FPM Socket: The fastcgi_pass directive points to the PHP FastCGI Process Manager (FPM) socket. In this example, the configuration shows php8.3-fpm.sock for Ubuntu 24.04. Be sure to adjust this to match your PHP version (8.1 for 22.04, 8.4 for 26.04).

Security and Access Controls

In addition, the configuration includes several security-focused directives:

  • Access Restriction:
    • PHP File Access: By using the location ~* ^.+\.php$ block, access to all other PHP files is restricted, which enhances security by preventing unauthorized script execution.
    • Directory Access: Similarly, the location ~ /(config|tmp|core|lang) block denies access to sensitive Matomo directories, protecting them from external access.
    • .htaccess Access: Additionally, the location ~ /\.ht block restricts access to .htaccess files, which is an important security measure.
  • Static File Handling: The location ~ \.(gif|ico|jpg|png|svg|js|css|htm|html|mp3|mp4|wav|ogg|avi|ttf|eot|woff|woff2|json)$ block allows access to various static file types and also implements caching to improve loading times.
  • Denied Access: The location ~ /(libs|vendor|plugins|misc/user) block prevents access to specific directories, which adds an extra layer of security.
  • Text File Display: The location ~/(.*\.md|LEGALNOTICE|LICENSE) block ensures that markdown and legal text files are displayed correctly in the browser.

After editing, save and close the file (in nano, press Ctrl+O to save, then Ctrl+X to exit). Next, enable the site by creating a symbolic link, test the configuration syntax, and restart Nginx:

sudo ln -s /etc/nginx/sites-available/matomo.conf /etc/nginx/sites-enabled/
sudo nginx -t

If successful, a syntax test returns:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Once the test passes, restart Nginx to apply the configuration:

sudo systemctl restart nginx

Setting Up MariaDB for Matomo

Essentially, configuring MariaDB correctly is essential for the efficient and secure operation of Matomo. Below is an expanded guide to set up MariaDB for your installation:

Accessing MariaDB

To start, access the MariaDB console. This interface allows you to execute commands directly to the database server:

sudo mysql -u root -p

or

sudo mariadb -u root -p

If you have not set a root password yet, you may be able to access the database without one.

Creating a Dedicated Database User

As a best practice, use a dedicated user for each application to limit permissions and enhance security. Create a new user for Matomo within MariaDB:

CREATE USER 'matomo_user'@'localhost' IDENTIFIED BY 'secure_password';

Be sure to replace secure_password with a strong, unique password. In particular, this dedicated user reduces the risk of unauthorized database access.

Creating a Database for Matomo

Since Matomo requires its own database, create a dedicated database using the following command:

CREATE DATABASE matomo_db;

In this example, matomo_db is the name of the new database. Of course, feel free to choose any name that suits your naming conventions.

Granting Privileges

Now grant the user full access to the Matomo database:

GRANT ALL PRIVILEGES ON matomo_db.* TO 'matomo_user'@'localhost';

Essentially, this command assigns all necessary permissions for matomo_user on matomo_db, which ensures Matomo can perform required database operations.

Applying Changes

To apply these changes, flush the privileges. This command tells MariaDB to reload the grant tables:

FLUSH PRIVILEGES;

Finally, exit the MariaDB console:

EXIT;

Configure Cron Job for Matomo Archiving

Matomo processes raw visit data and generates reports through a scheduled archiving task. Without this cron job, reports would be generated on-demand when you view the dashboard, which would slow down the interface and increase server load.

To set this up, open the crontab for the www-data user (the same user that runs Nginx and PHP-FPM):

sudo crontab -e -u www-data

If prompted, select a text editor (nano is usually option 1). Then add the following line to schedule archiving every hour at the fifth minute:

5 * * * * php /var/www/html/matomo/console core:archive > /var/log/matomo-archive.log 2>&1

After saving, exit the editor. This cron job runs the Matomo archiving command every hour, pre-generating reports so the dashboard loads quickly. The 2>&1 redirects both standard output and errors to the log file for troubleshooting.

Install Matomo Front-End via Nginx

Navigating the Matomo Installation Process

Opening the Matomo Web Interface

Begin by accessing Matomo through your web browser. Use the URL assigned to your Matomo instance, which is typically structured as http://your-domain.com/matomo or http://your-server-ip/matomo.

Welcome Screen and Introduction

First, the welcome screen introduces you to Matomo’s setup process. In particular, this initial page serves as a starting point, outlining the steps you will follow during the installation.

Performing a System Check

Ensuring Server Compatibility

During this step, Matomo automatically inspects your server environment to verify compatibility. Key checks include:

  • PHP Version: Ensuring the server runs a compatible PHP version.
  • PHP Extensions: Checking for essential PHP extensions needed by Matomo.
  • File Permissions: Verifying that Matomo files have the correct permissions.
  • Database Support: Confirming the availability of necessary database extensions.

If any issues are highlighted, address them before proceeding.

Database Configuration

Setting Up Database Connection

Configure the connection to your MariaDB database:

  • Database Server: Typically, this is localhost.
  • Login: Use the username created for your Matomo database (e.g., matomo_user).
  • Password: Enter the password you assigned to your Matomo database user.
  • Database Name: Specify the name of your Matomo database (e.g., matomo_db).

After filling in these details, click “Next” to move forward.

Super User Account Creation

Create the primary administrative account for managing Matomo:

  • Username: Choose a unique username.
  • Password: Select a strong and secure password.
  • Email Address: Provide a valid email for account recovery and notifications.

As a result, this account will have comprehensive access to Matomo’s settings and analytics data.

Setting Up Your First Website

Configure the initial website you want Matomo to track:

  • Website Name: Enter the name of your site.
  • Website URL: Provide the full URL of the website you’re tracking.

Additionally, Matomo inquires about sharing anonymized usage data to enhance the platform.

Implementing the JavaScript Tracking Code

At this point, Matomo generates a JavaScript tracking code for your website. Ideally, this code should be embedded in your website’s HTML just before the </head> tag. This integration is critical for Matomo to track visitor data on your site.

Completing the Setup

Confirmation and Finalization

Once you have implemented the tracking code, confirm your setup in Matomo. Subsequently, the system will complete the installation process.

Accessing the Dashboard

After installation, you gain access to the Matomo dashboard. Here, analytical data will populate as Matomo begins tracking your website.

Matomo Post-Installation Tips

Note that these configuration examples are optional optimizations. The default settings work well for most installations. Only modify these values if you understand the performance implications and have specific requirements.

Customizing Report Row Limits

By default, Matomo limits the number of rows stored in reports to prevent database bloat. However, for high-traffic sites that need more detailed analytics, you can increase these limits in the config/config.ini.php file.

Open the configuration file:

sudo nano /var/www/html/matomo/config/config.ini.php

Then add or modify these lines under the [General] section to increase the row limits from the default of 500:

[General]
datatable_archiving_maximum_rows_referrers = 5000
datatable_archiving_maximum_rows_subtable_referrers = 5000
datatable_archiving_maximum_rows_actions = 5000
datatable_archiving_maximum_rows_subtable_actions = 5000
datatable_archiving_maximum_rows_events = 5000
datatable_archiving_maximum_rows_subtable_events = 500
datatable_archiving_maximum_rows_site_search = 5000

As a result, these settings cap reports at 5000 rows instead of the default 500. While higher values provide more granular data, they also increase database size and processing time during archiving.

Performance Considerations

Keep in mind that increasing row limits affects archiving performance. If you set very high limits (100,000+), expect longer archiving times and larger database tables. Therefore, monitor your archive cron job logs at /var/log/matomo-archive.log to ensure archiving completes within the hourly schedule. If archiving takes longer than an hour, reduce the row limits or upgrade your server resources.

For detailed configuration options including custom dimensions, media analytics, and premium plugin settings, consult the Matomo documentation.

Secure Matomo and Nginx with Let’s Encrypt SSL Free Certificate

Implementing SSL on Nginx for Enhanced Security

Securing your Matomo analytics platform and Nginx server with an SSL certificate is essential for web server security. Fortunately, Let’s Encrypt provides a free, automated certificate authority that allows you to easily set up SSL certificates for your Nginx server.

Installing Certbot for SSL Certificate Management

First, install the Certbot package. This tool simplifies obtaining and renewing Let’s Encrypt SSL certificates:

sudo apt install python3-certbot-nginx

Generating Your SSL Certificate

Once Certbot is installed, generate your SSL certificate. Be sure to replace the email and domain with your actual values:

sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email your-email@example.com -d matomo.example.com

In particular, the flags used in this command configure a comprehensive SSL setup:

  • --redirect: Automatically redirects all HTTP traffic to HTTPS
  • --hsts: Adds the Strict-Transport-Security header to enforce HTTPS
  • --staple-ocsp: Enables OCSP stapling for improved SSL performance

During installation, the Electronic Frontier Foundation (EFF) may prompt you to subscribe to their newsletter. Respond as you prefer to complete the certificate installation.

Transitioning to HTTPS

After the certificate is installed, your website’s URL will update from HTTP to HTTPS, automatically redirecting any old HTTP URL accesses to the secure HTTPS URL.

Automating SSL Certificate Renewal

To maintain your SSL certificate’s validity, you should verify that automatic renewal is configured.

Testing Automatic Renewal

Test the renewal process with a dry run:

sudo certbot renew --dry-run

Verify Automatic Renewal

Ubuntu’s Certbot package includes a systemd timer that handles automatic renewal. Verify the timer is active:

systemctl status certbot.timer

When active, the output will show active (waiting):

● certbot.timer - Run certbot twice daily
     Loaded: loaded (/lib/systemd/system/certbot.timer; enabled; preset: enabled)
     Active: active (waiting) since ...
    Trigger: ...

As a result, this timer runs Certbot twice daily and renews certificates when they are within 30 days of expiration. Therefore, no manual cron job is needed.

Troubleshooting Common Issues

502 Bad Gateway Error

A 502 error typically indicates that Nginx cannot communicate with PHP-FPM. Since the most common cause is an incorrect socket path in the Nginx configuration, first verify which PHP-FPM sockets are available:

ls /run/php/

If successful, the output lists the available sockets:

php8.3-fpm.pid  php8.3-fpm.sock  php-fpm.sock

Ensure the socket name in your Nginx configuration (/etc/nginx/sites-available/matomo.conf) matches one of the sockets shown. Additionally, verify PHP-FPM is running:

systemctl status php8.3-fpm

Be sure to replace php8.3-fpm with your PHP version. If the service shows inactive or failed, restart it with sudo systemctl restart php8.3-fpm.

Database Connection Failed

If Matomo cannot connect to MariaDB during installation, first verify the database credentials and confirm that the user has proper permissions:

sudo mariadb -e "SHOW GRANTS FOR 'matomo_user'@'localhost';"

If successful, the output shows the user’s privileges:

+-------------------------------------------------------+
| Grants for matomo_user@localhost                      |
+-------------------------------------------------------+
| GRANT USAGE ON *.* TO `matomo_user`@`localhost` ...   |
| GRANT ALL PRIVILEGES ON `matomo_db`.* TO ...          |
+-------------------------------------------------------+

If the user does not exist or lacks the GRANT ALL PRIVILEGES ON matomo_db.* line, recreate it using the database setup commands from earlier in this guide.

Permission Denied Errors

If Matomo displays errors about writing to the tmp or config directories, fix the file ownership:

sudo chown -R www-data:www-data /var/www/html/matomo
sudo find /var/www/html/matomo -type d -exec chmod 755 {} \;
sudo find /var/www/html/matomo -type f -exec chmod 644 {} \;

Archive Cron Not Running

If Matomo is generating reports slowly, verify the archive cron job is running by checking its log:

sudo tail -20 /var/log/matomo-archive.log

Should the log be empty or missing, verify the cron job exists:

sudo crontab -l -u www-data

If configured correctly, the output includes the archive command:

5 * * * * php /var/www/html/matomo/console core:archive > /var/log/matomo-archive.log 2>&1

Should the cron job be missing, re-add it using the cron job setup instructions from earlier in this guide.

Remove Matomo from Ubuntu

To completely remove Matomo from your system, follow these steps to clean up all components installed during this guide.

Remove Matomo Files and Nginx Configuration

Warning: The following commands permanently delete all Matomo files and analytics data. Be sure to export any reports or data you want to keep before proceeding.

First, remove the Matomo installation directory and Nginx configuration:

sudo rm -rf /var/www/html/matomo
sudo rm /etc/nginx/sites-enabled/matomo.conf
sudo rm /etc/nginx/sites-available/matomo.conf
sudo systemctl reload nginx

Remove the Database and User

Connect to MariaDB and drop the Matomo database along with its dedicated user:

sudo mariadb

Run the following SQL commands:

DROP DATABASE IF EXISTS matomo_db;
DROP USER IF EXISTS 'matomo_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

Remove the Cron Job

Remove the archiving cron job from the www-data user:

sudo crontab -r -u www-data

Note that this command removes all cron jobs for the www-data user. If other applications use cron jobs under this user, edit the crontab manually with sudo crontab -e -u www-data and remove only the Matomo line.

Remove the SSL Certificate (Optional)

If you created an SSL certificate for Matomo, you can revoke and delete it:

sudo certbot delete --cert-name matomo.example.com

Replace matomo.example.com with the domain you used when creating the certificate.

Note that the LEMP stack components (Nginx, MariaDB, PHP) remain installed as they may be used by other applications. If you want to remove them as well, run sudo apt remove --purge nginx mariadb-server php-fpm followed by sudo apt autoremove.

Verify the removal was successful:

ls /var/www/html/matomo 2>/dev/null || echo "Matomo directory removed"
nginx -t

In essence, the first command confirms the Matomo directory no longer exists, while nginx -t verifies the Nginx configuration is valid after removing the Matomo server block.

Conclusion

As a result, you now have a fully functional Matomo analytics platform running on your Ubuntu server. Importantly, the LEMP stack provides a solid foundation, and the Let’s Encrypt SSL certificate ensures secure data transmission between your visitors and your analytics server.

After completing the web installer, consider these next steps for a production environment:

  • Enable two-factor authentication in the Matomo admin panel for added security
  • Set up email reports to receive scheduled analytics summaries
  • Configure data retention policies to manage database growth
  • Install plugins from the Matomo Marketplace to extend functionality

For additional Nginx optimization, consider setting up FastCGI caching on Ubuntu to reduce PHP processing load, enabling gzip compression in Nginx to speed up page delivery, and configuring security headers to protect against common web vulnerabilities.

Matomo handles its own updates through the admin interface, so you can update to new versions directly from the dashboard when they become available. For production deployments tracking significant traffic, monitor the archive cron job logs and consider the performance tuning options in the Matomo official documentation.

Leave a Comment