Cómo instalar Matomo (Piwik) Web Analytics en CentOS 8

Matomo, antes conocido como Piwik, es una aplicación de análisis de código abierto para el sistema operativo Linux. Es muy similar a Google Analytics, que te ayuda a rastrear y mostrar la ubicación de las visitas de los usuarios. Fue desarrollada por un equipo de desarrolladores internacionales que se ejecuta en un servidor web PHP/MySQL. Ofrece muchas características, algunas de las cuales se enumeran a continuación

  • Flexibilidad, fiabilidad y seguridad
  • Autoalojado, sencillo y fácil de usar
  • 100% de propiedad de los datos
  • Cumplimiento del GDPR
  • Análisis web y móvil

En este tutorial, te mostraremos cómo instalar y configurar la aplicación de análisis Piwik en un servidor CentOS 8.

Requisitos previos

  • Un servidor con CentOS 8.
  • Un nombre de dominio válido apuntado con la IP de tu servidor.
  • Una contraseña de root configurada en tu servidor.

Instalar un servidor LAMP

Piwik se ejecuta en un servidor LAMP, por lo que tendrás que instalar en tu sistema el Apache, MariaDB, PHP y otras extensiones de PHP. Puedes instalarlos todos con el siguiente comando:

dnf install httpd mariadb-server php php-mysqlnd php-fpm unzip wget php-json php-dom php-gd php-mbstring -y

Una vez instalados todos los paquetes, edita el archivo php.ini y establece algunos valores deseados:

nano /etc/php.ini

Cambia los siguientes valores:

upload_max_filesize = 10M
post_max_size = 10M
max_execution_time = 300
max_input_time = 300
memory_limit = 256M

Guarda y cierra el archivo y luego inicia el servicio de Apache y MariaDB y permite que se inicien al reiniciar el sistema:

systemctl start mariadb
systemctl start httpd
systemctl enable mariadb
systemctl enable httpd

Crear una base de datos para Piwik

A continuación, tendrás que crear una base de datos y un usuario para Piwik. En primer lugar, inicia sesión en MariaDB con el siguiente comando:

mysql

Una vez iniciada la sesión, crea una base de datos y un usuario con el siguiente comando:

mysql> CREATE DATABASE matomo;
mysql> CREATE USER `matomo`@`localhost` IDENTIFIED BY 'password';

A continuación, concede todos los privilegios a la base de datos con el siguiente comando:

mysql> GRANT ALL ON matomo.* TO `matomo`@`localhost`;

A continuación, vacía los privilegios y sal de MariaDB con el siguiente comando:

mysql> FLUSH PRIVILEGES;
mysql> EXIT;

Instalar Piwik

A continuación, deberás descargar la última versión de Piwik desde su sitio web oficial. En primer lugar, cambia el directorio a la raíz web de Apache con el siguiente comando:

cd /var/www/html

A continuación, descarga el Piwik con el siguiente comando:

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

Una vez completada la descarga, descomprime el archivo descargado con el siguiente comando:

unzip matomo-latest.zip

A continuación, establece el permiso y la propiedad adecuados a la raíz de la web con el siguiente comando:

chown -R apache:apache /var/www/html/matomo
chmod -R 775 /var/www/html/matomo

Una vez que hayas terminado, puedes pasar al siguiente paso.

Configurar SELinux y el cortafuegos

A continuación, tendrás que permitir los puertos 80 y 443 a través del cortafuegos. Puedes permitirlos con el siguiente comando:

firewall-cmd --permanent --zone=public --add-service=http
firewall-cmd --permanent --zone=public --add-service=https

A continuación, recarga el firewalld para aplicar los cambios:

firewall-cmd --reload

A continuación, también tendrás que configurar SELinux para Piwik. Puedes configurarlo con el siguiente comando:

chcon -R -t httpd_sys_rw_content_t /var/www/html/matomo/
setsebool httpd_can_network_connect on -P

Una vez que hayas terminado, puedes pasar al siguiente paso.

Configurar Apache para Piwik

A continuación, tendrás que configurar el servidor web Apache para alojar el sitio web de Piwik. Puedes hacerlo creando un nuevo archivo de configuración del host virtual de Apache:

nano /etc/httpd/conf.d/piwik.conf

Añade las siguientes líneas:

<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "/var/www/html/matomo"
ServerName piwik.example.com
<Directory "/var/www/html/matomo/">
Options MultiViews FollowSymlinks
AllowOverride All
Order allow,deny
Allow from all
</Directory>
TransferLog /var/log/httpd/matomo_access.log
ErrorLog /var/log/httpd/matomo_error.log

</VirtualHost>

Guarda y cierra el archivo cuando hayas terminado. A continuación, reinicia el servidor web Apache para aplicar los cambios:

systemctl restart httpd

Ahora puedes comprobar el estado del Apache con el siguiente comando:

systemctl status httpd

Deberías obtener la siguiente salida:

? httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
  Drop-In: /usr/lib/systemd/system/httpd.service.d
           ??php-fpm.conf
   Active: active (running) since Sun 2020-12-27 05:38:29 EST; 5s ago
     Docs: man:httpd.service(8)
 Main PID: 4228 (httpd)
   Status: "Started, listening on: port 80"
    Tasks: 213 (limit: 12523)
   Memory: 36.8M
   CGroup: /system.slice/httpd.service
           ??4228 /usr/sbin/httpd -DFOREGROUND
           ??4229 /usr/sbin/httpd -DFOREGROUND
           ??4230 /usr/sbin/httpd -DFOREGROUND
           ??4231 /usr/sbin/httpd -DFOREGROUND
           ??4232 /usr/sbin/httpd -DFOREGROUND

Dec 27 05:38:28 centos8 systemd[1]: Stopped The Apache HTTP Server.
Dec 27 05:38:28 centos8 systemd[1]: Starting The Apache HTTP Server...

Una vez que hayas terminado, puedes pasar al siguiente paso.

Acceder a la interfaz web de Piwik

Ahora, abre tu navegador web y accede a la interfaz web de Piwik utilizando la URL http://piwik.example.com. Serás redirigido a la siguiente página:

Instalador de Piwik

Haz clic en el SIGUIENTE, deberías ver la página de comprobación del sistema:

Comprobación del sistema

Haz clic en SIGUIENTE, deberías ver la página de configuración de la base de datos:

Configuración de la base de datos

Proporciona tu nombre de usuario de la base de datos, el nombre de la base de datos, la contraseña y haz clic en SIGUIENTE, deberías ver la siguiente página:

Crear tablas de la base de datos

Haz clic en SIGUIENTE, deberías ver la página de creación del usuario administrador:

Añadir una cuenta de usuario de administrador

Proporciona tu nombre de usuario de administrador, contraseña, correo electrónico y haz clic en SIGUIENTE. Deberías ver la página de configuración del sitio web:

Crear un sitio web

Proporciona los detalles de tu sitio web y haz clic en SIGUIENTE. Deberías ver el código de seguimiento en la siguiente página:

Código de seguimiento JS para Piwik

Análisis de registros

Haz clic en el SIGUIENTE. Una vez terminada la instalación. Deberías ver la siguiente página:

Instalación terminada

Haz clic en el botón CONTINUAR a MATOMO. Deberías ver la página de inicio de sesión de MATOMO:

Inicio de sesión en Matomo

Introduce tu nombre de usuario y contraseña de administrador y haz clic en el botón INICIAR SESIÓN. Deberías ver el panel de control de MATOMO en la siguiente página:

Tablero de estadísticas

Asegura Matomo con Let’s Encrypt SSL

A continuación, tendrás que instalar la utilidad Certbot en tu sistema para descargar e instalar Let’s Encrypt SSL para tu sitio web de Piwik.

Puedes instalar el cliente Certbot con el siguiente comando:

wget https://dl.eff.org/certbot-auto
mv certbot-auto /usr/local/bin/certbot-auto
chown root /usr/local/bin/certbot-auto
chmod 0755 /usr/local/bin/certbot-auto

A continuación, obtén e instala un certificado SSL para tu sitio web Mantis con el siguiente comando:

certbot-auto --apache -d piwik.example.com
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator apache, Installer apache
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): [email protected]

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: A

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y 


Obtaining a new certificate
Performing the following challenges:
http-01 challenge for piwik.example.com
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/httpd/conf.d/piwik.conf

A continuación, tendrás que elegir si quieres redirigir el tráfico HTTP a HTTPS como se muestra a continuación:

Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2

Escribe 2 y pulsa Enter para continuar. Una vez terminada la instalación, deberías ver la siguiente salida:

Redirecting all traffic on port 80 to ssl in /etc/httpd/conf.d/piwik.conf

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://piwik.example.com

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=piwik.example.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/piwik.example.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/piwik.example.com/privkey.pem
   Your cert will expire on 2020-03-23. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot-auto
   again with the "certonly" option. To non-interactively renew *all*
   of your certificates, run "certbot-auto renew"
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

En este punto, tu sitio web está protegido con Let’s Encrypt SSL.

Conclusión ¡Enhorabuena! has instalado y configurado con éxito Piwik con Apache y Let’s Encrypt SSL en CentOS 8. Ahora puedes añadir tu código de seguimiento en tu sitio web y empezar a monitorizar los visitantes de tu sitio web desde el panel de control de Piwik. No dudes en preguntarme si tienes alguna duda.

También te podría gustar...