How to Install Matomo with Nginx on Ubuntu 24.04/22.04/20.04

Matomo, known for its comprehensive analytics capabilities, offers a powerful platform for webmasters, developers, and administrators to track and understand website traffic. It stands out for its versatility in providing detailed insights, making it a top choice for those seeking an alternative to mainstream analytics tools.

Key Features of Matomo:

  • Privacy and Data Ownership: Prioritizes user privacy, with full data ownership resting with the user.
  • Customizable Dashboard: Offers a highly customizable interface for tracking key metrics.
  • Real-time Data Updates: Provides real-time updates on website traffic and user interactions.
  • E-commerce Tracking: Supports detailed e-commerce tracking, offering insights into customer behavior and sales trends.
  • Event Tracking: Captures and analyzes specific user actions on your website.
  • Goal Conversion Tracking: Enables the tracking of specific goals and conversions.
  • Search Engine Optimization: Offers tools for effective SEO monitoring.

With the recent release of Matomo 5.0 on December 19, 2023, users can expect enhanced performance, new features, and improved usability, marking a significant milestone in its development compared with the older 4.x releases.

The following sections will guide you through installation, ensuring you can leverage these powerful features on your Ubuntu system.

Install Nginx – LEMP PART 1

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, as Matomo is a complex application.

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

sudo apt update && sudo apt upgrade

This command refreshes your package list and upgrades your system, ensuring it is up-to-date.

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

These packages are vital for Matomo’s various installation and operational processes.

Install Nginx via APT Command

Begin building your LEMP stack by installing Nginx. Execute this command to install Nginx:

sudo apt install nginx

After installation, verify that Nginx is running correctly with this command:

systemctl status nginx

If Nginx is not active, enable it with this command:

sudo systemctl enable nginx --now

Additional: Install Nginx Mainline for Enhanced Matomo Performance

For optimal Matomo performance, consider installing the latest Nginx mainline version. 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 delving into specific configurations, it’s essential to understand the available UFW profiles for Nginx. Each profile caters to different requirements of web server operation.

  • 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

Next, specify which profile you want to use, for example, ‘Nginx Full’:

sudo ufw allow 'Nginx Full'

Customizing UFW Rules

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

Restrict Access to Specific IP Addresses

To enhance security, you might want to allow access to Nginx only from certain IP addresses:

sudo ufw deny from 192.168.1.100

This command blocks all incoming traffic from the IP address 192.168.1.100.

Deleting Rules

Mistakes happen, and you might need to delete a rule. First, list all rules with their numbers:

sudo ufw status numbered

Then delete a specific rule (for example, rule number 2) with:

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 – LEMP PART 2

Installing MariaDB for Matomo

MariaDB, a preferred database for the LEMP stack, offers enhanced performance over MySQL. For those requiring 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.

Install MariaDB with the following command:

sudo apt install mariadb-server mariadb-client

Verifying MariaDB Service Status

After installation, it’s essential to check the status of MariaDB to ensure its proper functionality:

systemctl status mariadb

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. Default settings in new installations might be vulnerable to attacks. The mysql_secure_installation script enhances security significantly.

Initiate the security configuration process with this command:

sudo mysql_secure_installation

During this process, you’ll set the root password, restrict remote access, remove anonymous users, and delete the test database. Each step fortifies the security of your MariaDB setup, safeguarding your Matomo installation from potential threats.

Example:

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
haven't set the root password yet, you should just press enter here.

Enter current password for root (enter for none): 
OK, successfully used password, moving on...

Setting the root password or using the unix_socket ensures that nobody
can log into the MariaDB root user without the proper authorisation.

You already have your root account protected, so you can safely answer 'n'.

Switch to unix_socket authentication [Y/n] Y <---- Type Y then press the ENTER KEY.
Enabled successfully!
Reloading privilege tables..
 ... Success!


You already have your root account protected, so you can safely answer 'n'.

Change the root password? [Y/n] Y <---- Type Y then press the ENTER KEY.
New password: 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] Y <---- Type Y then press the ENTER KEY.
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] Y <---- Type Y then press the ENTER KEY.
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] Y <---- Type Y then press the ENTER KEY.
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] Y <---- Type Y then press the ENTER KEY.
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

Install PHP – LEMP PART 3

Installing PHP for Matomo

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

To install PHP along with PHP-FPM and the modules required by Matomo, execute this command:

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

This command installs PHP and its modules, ensuring compatibility and functionality for Matomo.

Verifying PHP Service Status

Post-installation, confirm that the PHP service is operational. The command varies based on the installed PHP version. For PHP 8.1, use:

systemctl status php8.1-fpm

The status check verifies that PHP-FPM is active and running, ensuring that PHP processes requests as intended for Matomo. If you are unsure which PHP version is installed on your Ubuntu system, run the following command:

php --version

Just as in the previous example visual image, you can see the printed version of the PHP version, which now you can check the status of PHP-FPM, etc.

Configure Matomo Backend

Downloading and Setting Up Matomo

Downloading Matomo

To start, 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

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

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

Extracting the Matomo Archive

Extract the downloaded .tar.gz file into the Matomo directory. 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

This command extracts the files, while --strip-components=1 removes the top-level directory from the archive, placing the contents directly into the Matomo directory.

You can print in your terminal the contents of the extracted Matomo archive to ensure everything looks correct with the following command:

ls /var/www/html/matomo

Configuring File Permissions for Matomo

Proper file permissions ensure Matomo’s security and correct functioning.

Directories Permissions

Set the permissions for directories to allow adequate access:

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

This command changes the permissions of directories to 755, the standard for web directories.

Files Permissions

Apply the correct permissions to the files:

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

Setting files to 644 permits reading and writing by the owner and read-only access for others, balancing security and functionality.

Configuring Nginx for Matomo

Set up a server block in Nginx to serve your Matomo application:

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

Then, add the following configuration:

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/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/php7.4-fpm.sock; 
    }
    
    location = /plugins/HeatmapSessionRecording/configs.php { 
        include snippets/fastcgi-php.conf;
        fastcgi_param HTTP_PROXY "";
        fastcgi_pass unix:/run/php/php7.4-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

The Nginx configuration file for Matomo is structured to ensure optimal performance and security. Here’s a more detailed breakdown of its key components:

  • HTTP Listening: The listen directives configure Nginx to listen on port 80 for both IPv4 and IPv6. This setup is crucial for handling web traffic.
  • Server Name: The server_name directive specifies the domain name for the Matomo instance, essential for directing requests to the correct server block.
  • Logging: The access_log and error_log directives 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. The index directive specifies that index.php should be the default file to serve.
  • PHP File Processing:
    • Specific PHP Files: The location ~ ^/(index|matomo|piwik|js/index).php block includes settings for processing main PHP files of Matomo. It prevents the httpoxy vulnerability using fastcgi_param HTTP_PROXY "";.
    • Heatmap Plugin: The location = /plugins/HeatmapSessionRecording/configs.php block is tailored for the HeatmapSessionRecording plugin, ensuring it functions correctly.
    • PHP-FPM Socket: The fastcgi_pass directive points to the PHP FastCGI Process Manager (FPM) socket. Adjust php7.4-fpm.sock to match your PHP version.
  • Access Restriction:
    • PHP File Access: The location ~* ^.+\.php$ block restricts access to all other PHP files, enhancing security by preventing unauthorized script execution.
    • Directory Access: The location ~ /(config|tmp|core|lang) block denies access to sensitive Matomo directories, protecting them from external access.
    • .htaccess Access: The location ~ /\.ht block restricts access to .htaccess files, 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 implements caching to improve loading times.
  • Denied Access: The location ~ /(libs|vendor|plugins|misc/user) block prevents access to specific directories, adding 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. Then, enable the site and test the configuration:

sudo ln -s /etc/nginx/sites-available/matomo /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

Setting Up MariaDB for Matomo

Configuring MariaDB correctly is a key step in ensuring the efficient and secure operation of Matomo. Here’s an expanded guide to set up MariaDB for your Matomo installation:

Accessing MariaDB

First, 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

Enter your root password when prompted. If you haven’t set a root password yet, you may be able to access the database without a password.

Creating a Dedicated Database User

It’s a best practice to use a dedicated user for each application. This limits permissions and enhances security. Create a new user for Matomo within MariaDB:

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

Replace secure_password with a strong, unique password. This user will be used solely for Matomo, reducing the risk of unauthorized database access.

Creating a Database for Matomo

Matomo requires its own database. Create a dedicated database for Matomo using the following command:

CREATE DATABASE matomo_db;

matomo_db is the name of the new database. You can choose any name that suits your naming conventions.

Granting Privileges

After creating the new user and database, grant the user full access to the Matomo database:

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

This command assigns all necessary permissions for matomo_user on matomo_db, ensuring Matomo can perform required database operations.

Applying Changes

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

FLUSH PRIVILEGES;

Finally, exit the MariaDB console:

EXIT;

Creating a Cron Job for Matomo Analytics

Setting Up a User-Specific Cron Job

Optimizing Matomo analytics performance involves configuring a user-specific cron job, which ensures consistent and efficient data processing.

Editing the Crontab for a Specific User

Begin by opening the crontab configuration for a specific user, typically www-data, who usually runs the web server. Use the command:

sudo crontab -e -u www-data

If prompted, select a text editor. In the crontab file, add the line:

5 * * * * www-data php /path/to/matomo/console core:archive > /var/log/matomo-archive.log

This command schedules the Matomo archiving process at the fifth minute of every hour. The php command initiates the script, and the path leads to Matomo’s console script, with core:archive triggering the archiving. The output is redirected to a log file for monitoring.

Install Matomo Front-End via Nginx

Navigating the Matomo Installation Process

Opening the Matomo Web Interface

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

Welcome Screen and Introduction

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

Performing a System Check

Ensuring Server Compatibility

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.

Address any highlighted issues to proceed smoothly.

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).

Fill in these details and 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.

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.

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

Implementing the JavaScript Tracking Code

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

After implementing the tracking code, confirm your setup in Matomo. The system will then complete the installation process.

Accessing the Dashboard

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

Matomo Post-Installation Tips

Note: These examples are to fine-tune and often rely on how much resources your server has. For newer users, stick with the defaults until you are comfortable with Matomo.

Customizing Report Rows in Matomo

Setting Maximum Rows for Standard Reports

To tailor the number of entries in standard Matomo reports, modify the config/config.ini.php file. This configuration helps manage data volume in reports like referrers, actions, and events.

If you used the guide’s configuration setup, the config.ini.php file should be located at:

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

Add the following lines under the [General] section:

[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 = 100
datatable_archiving_maximum_rows_site_search = 5000
datatable_archiving_maximum_rows_userid_users = 5000

This configuration sets a cap of 5000 rows for various tables and subtables, ensuring manageable data presentation.

Adjusting Custom Dimensions and Reports

Custom Dimensions Rows Limit

Similar adjustments can be made for users utilizing Custom Dimensions and/or Custom Variables plugins. These settings control the data volume for custom dimensions, aligning it with your reporting needs.

Custom Reports Adjustments

If you’re using the Custom Reports premium feature, you can tailor these settings to align with your specific reporting requirements.

Media Analytics Configuration

For those using the Media Analytics premium feature, there are also customizable settings to manage data volume and report granularity.

Managing Other Report Limits

Location Reports Customization

Some reports, like Location reports (Regions & Cities), don’t have a specific row limit in the config.ini.php file. By default, this limit is 500, but you can modify it by adding:

; Adjust the row limit for Location reports
your_custom_row_limit_for_location_reports = 500

Replace your_custom_row_limit_for_location_reports with your desired limit.

Reprocessing Reports with New Row Limits

After changing these settings, you might want to reprocess old reports to reflect the new row limits. Consult the Matomo FAQ on reprocessing reports for guidance on this process.

Archiving All Data (Unlimited Rows)

For comprehensive data archiving, set a high limit, like one million:

; Set a high limit for archiving all data
your_high_limit_setting = 1000000

Important Note on Performance

Be aware that setting very high limits can significantly impact the performance of archiving and application processes. It’s crucial to balance data comprehensiveness with system capabilities.

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 bolsters web server security. Let’s Encrypt, a free, automated certificate authority, allows you to easily set up SSL certificates for your Nginx server.

Installing Certbot for SSL Certificate Management

Start by installing the Certbot package. This tool simplifies obtaining and renewing Let’s Encrypt SSL certificates:

sudo apt install python3-certbot-nginx

Generating Your SSL Certificate

After installing Certbot, generate your SSL certificate using the following command:

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

During the certificate installation, the Electronic Frontier Foundation (EFF) may prompt you regarding email updates. Respond accordingly to initiate the automatic installation and configuration of your certificate.

This command ensures a comprehensive SSL setup, including HTTPS 301 redirects, a Strict-Transport-Security header, and OCSP Stapling. Remember to customize the email and domain name to suit your needs.

Transitioning to HTTPS

Once 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

Maintaining your SSL certificate’s validity requires setting up an automatic renewal process.

Testing Automatic Renewal

Test the renewal process with a dry run:

sudo certbot renew --dry-run

Configuring a Root Cron Job

To set up the cron job as the root user, open the root crontab:

sudo crontab -e

In the crontab, schedule a daily task for certificate renewal:

00 00 */1 * * certbot renew

This configuration ensures your Nginx server, hosting Matomo analytics, remains secure with a continuously valid SSL certificate.

Conclusion

That wraps up our comprehensive guide on setting up Matomo with LEMP stack on Ubuntu 22.04 or 20.04. We’ve covered everything from initial installation to fine-tuning reports and custom configurations. Remember, the key to getting the most out of Matomo lies in regular updates and keeping an eye on performance, especially if you dive into detailed analytics. Don’t forget to back up your configurations before making significant changes, and most importantly, enjoy the insights Matomo brings to your website’s data landscape.

Leave a Comment