Cómo instalar PhpMyAdmin con Let’s Encrypt SSL gratuito en Ubuntu 22.04

phpMyAdmin es una aplicación gratuita, de código abierto y basada en web que se utiliza para gestionar bases de datos a través de un navegador web. Proporciona una interfaz web sencilla y fácil de usar que ayuda a los administradores de bases de datos a realizar varias tareas, gestionar cuentas de usuario y privilegios, importar y exportar datos, ejecutar sentencias SQL y mucho más. Está escrito en PHP, lo que permite a los usuarios principiantes interactuar con sus bases de datos MySQL.

En este tutorial, explicaremos cómo instalar phpMyAdmin con Nginx en Ubuntu 22.04.

Requisitos previos

  • Un servidor que ejecute Ubuntu 22.04.
  • Un nombre de dominio válido está apuntado con tu servidor.
  • Una contraseña de root está configurada en tu servidor.

Instalar Nginx, MariaDB y PHP

En primer lugar, tendrás que instalar el servidor web Nginx, MariaDB, PHP y otras extensiones PHP necesarias en tu servidor. Puedes instalarlos todos con el siguiente comando:

apt-get install nginx mariadb-server php php-cli php-mysql php-mbstring php-zip php-gd php-json php-curl php-fpm -y

Una vez instalados todos los paquetes, puedes pasar al siguiente paso.

Instalar phpMyAdmin

Por defecto, el paquete phpMyAdmin está disponible en el repositorio por defecto de Ubuntu 22.04. Puedes instalarlo simplemente ejecutando el siguiente comando:

apt-get install phpmyadmin -y

Durante la instalación, se te pedirá que selecciones el servidor web, como se muestra a continuación:

Instalar PHPMyAdmin

Como estamos utilizando el servidor web Nginx, puedes pulsar TAB y, a continuación, INTRO para omitir esta pregunta. Se te pedirá que configures una base de datos para que phpMyAdmin la utilice.

configurar PHPMyAdmin

Selecciona y pulsa Intro para continuar. Se te pedirá que elijas y confirmes una contraseña para la aplicación phpMyAdmin, como se muestra a continuación:

Contraseña de la aplicación MySQL

Introduce la contraseña que desees y pulsa Intro para finalizar la instalación.

Configurar la base de datos MariaDB

Por defecto, MariaDB no está protegida. Así que asegura MariaDB y establece la contraseña raíz de MariaDB con el siguiente comando:

mysql_secure_installation

Responde a todas las preguntas como se muestra a continuación:

Enter current password for root (enter for none): 
Set root password? [Y/n] Y
New password: 
Re-enter new password: 
Remove anonymous users? [Y/n] Y
Disallow root login remotely? [Y/n] Y
Remove test database and access to it? [Y/n] Y
Reload privilege tables now? [Y/n] Y

Después de proteger MariaDB, se recomienda crear un usuario independiente para conectarse a phpMyAdmin y gestionar la base de datos.

Para ello, accede al shell de MariaDB con el siguiente comando:

mysql -u root -p

Proporciona tu contraseña de root cuando se te solicite y, a continuación, crea un nuevo usuario con el siguiente comando:

MariaDB [(none)]> create user admin@localhost identified by 'password';

A continuación, concede todos los privilegios al usuario con el siguiente comando:

MariaDB [(none)]> grant all privileges on *.* to admin@localhost with grant option;

A continuación, vacía los privilegios y sal del intérprete de comandos MariaDB con el siguiente comando:

MariaDB [(none)]> flush privileges;
MariaDB [(none)]> exit;

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

Configurar Nginx para phpMyAdmin

A continuación, tendrás que crear un bloque de servidor host virtual Nginx para alojar phpMyAdmin. Puedes crearlo utilizando el siguiente comando:

nano /etc/nginx/conf.d/phpmyadmin.conf

Añade las siguientes líneas:

server {
  listen 80;
  listen [::]:80;
  server_name phpmyadmin.example.com;
  root /usr/share/phpmyadmin/;
  index index.php index.html index.htm index.nginx-debian.html;

  access_log /var/log/nginx/phpmyadmin_access.log;
  error_log /var/log/nginx/phpmyadmin_error.log;

  location / {
    try_files $uri $uri/ /index.php;
  }

  location ~ ^/(doc|sql|setup)/ {
    deny all;
  }

  location ~ \.php$ {
    fastcgi_pass unix:/run/php/php8.1-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    include snippets/fastcgi-php.conf;
  }

  location ~ /\.ht {
    deny all;
  }
}

Guarda y cierra el archivo. A continuación, comprueba si Nginx tiene algún error de sintaxis con el siguiente comando:

nginx -t

Deberías obtener la siguiente salida:

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

Por último, reinicia el servicio Nginx para aplicar los cambios:

systemctl restart nginx

También puedes comprobar el estado de Nginx con el siguiente comando:

systemctl status nginx

Deberías ver la siguiente salida:

? nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: active (running) since Sun 2022-06-12 04:37:05 UTC; 6s ago
       Docs: man:nginx(8)
    Process: 20020 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
    Process: 20021 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
   Main PID: 20022 (nginx)
      Tasks: 2 (limit: 2292)
     Memory: 2.6M
        CPU: 33ms
     CGroup: /system.slice/nginx.service
             ??20022 "nginx: master process /usr/sbin/nginx -g daemon on; master_process on;"
             ??20023 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""

Jun 12 04:37:05 ubuntu systemd[1]: Starting A high performance web server and a reverse proxy server...
Jun 12 04:37:05 ubuntu systemd[1]: Started A high performance web server and a reverse proxy server.

A continuación, cambia la propiedad y el permiso del directorio phpMyAdmin:

chown -R www-data:www-data /usr/share/phpmyadmin/
chmod -R 755

Asegura phpMyAdmin con Let’s Encrypt SSL

Antes de empezar, necesitarás instalar el cliente Certbot para descargar e instalar Let’s Encrypt SSL.

Primero, añade el repositorio de Certbot con el siguiente comando:

add-apt-repository ppa:ahasenack/certbot-tlssni01-1875471

A continuación, actualiza el repositorio e instala el cliente Certbot con el siguiente comando:

apt-get update -y
apt-get install certbot python3-certbot-nginx -y

Una vez instalado Certbot, ejecuta el siguiente comando para descargar e instalar Let’s Encrypt SSL para tu dominio:

certbot --nginx -d phpmyadmin.example.com

Se te pedirá que proporciones tu correo electrónico y aceptes las condiciones del servicio, como se muestra a continuación:

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
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 phpmyadmin.example.com
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/phpmyadmin

A continuación, selecciona si deseas o no redirigir el tráfico HTTP a HTTPS:

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 Intro para finalizar la instalación.

Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/phpmyadmin

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

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

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/phpmyadmin.example.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/phpmyadmin.example.com/privkey.pem
   Your cert will expire on 2022-09-12. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot again
   with the "certonly" option. To non-interactively renew *all* of
   your certificates, run "certbot 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

Accede a phpMyAdmin

Ahora, abre tu navegador web y escribe la URL https://phpmyadmin.eample.com. Se te redirigirá a la página de inicio de sesión de phpMyAdmin:

Inicio de sesión en PHPMyAdmin

Introduce tu nombre de usuario y contraseña de administrador, y pulsa el botón Ir. Deberías ver el panel de control predeterminado de phpMyAdmin en la página siguiente:

Interfaz web de PHPMyAdmin

Conclusión

Enhorabuena! has instalado correctamente phpMyAdmin y lo has protegido con Let’s Encrypt SSL en Ubuntu 22.04. Ahora puedes conectarte a phpMyAdmin, gestionar tus bases de datos y realizar varias tareas a través del navegador web.

También te podría gustar...