Cómo instalar Drupal con Nginx y Let's Encrypt en CentOS 8

27 feb 2021 6 min di lettura
Cómo instalar Drupal con Nginx y Let's Encrypt en CentOS 8
Indice dei contenuti

Introducción

Drupal es un sistema de gestión de contenido gratuito, de código abierto y escalable que se puede utilizar para crear y gestionar cualquier tipo de sitio web, está escrito en PHP y utiliza MySQL /MariaDB para almacenar sus datos. Drupal ofrece un amplio conjunto de funciones que se pueden ampliar con miles de complementos. Drupal admite muchos servidores web, incluidos Apache, Nginx, IIS, Lighttpd y MySQL, MariaDB, MongoDB, SQLite, PostgreSQL y bases de datos de servidor MS SQL. Drupal viene con una interfaz de usuario web simple e intuitiva que le permite crear sitios web sin ningún conocimiento de codificación.

En este tutorial, le mostraremos cómo instalar Drupal 8 en el servidor CentOS 8 y protegerlo con Let's Encrypt SSL gratuito.

Requisitos

  • Un servidor que ejecuta CentOS 8.
  • Un nombre de dominio válido indicado con la IP de su servidor
  • Usuario con privilegios de sudo.

Instale Nginx, MariaDB y PHP

Antes de comenzar, deberá instalar el servidor LEMP en su servidor. Puede instalarlo ejecutando el siguiente comando:

sudo dnf install nginx mariadb-server php php-fpm php-cli php-mbstring php-gd php-xml php-curl php-mysqlnd php-pdo php-json php-opcache -y

Una vez instalado, inicie Nginx, MariaDB y php-fpm y habilite el arranque después de reiniciar el sistema con el siguiente comando:

sudo systemctl start nginx
sudo systemctl start mariadb
sudo systemctl start php-fpm
sudo systemctl enable nginx
sudo systemctl enable php-fpm
sudo systemctl enable mariadb

Configurar bases de datos

De forma predeterminada, MariaDB no está protegida, por lo que deberá protegerla. Puede protegerlo ejecutando el siguiente comando:

mysql_secure_installation

Responda 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

Una vez hecho esto, inicie sesión en el shell MariaDB con el siguiente comando:

sudo mysql -u root -p

Proporcione su contraseña de root cuando se le solicite, luego cree una base de datos y un usuario para Drupal con el siguiente comando:

CREATE DATABASE drupaldb CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
CREATE USER drupal@localhost IDENTIFIED BY "password";

A continuación, conceda todos los privilegios a drupaldb con el siguiente comando:

GRANT ALL ON drupaldb.* TO drupal@localhost IDENTIFIED BY "password";

Luego, borre los privilegios y salga del shell MariaDB con el siguiente comando:

FLUSH PRIVILEGES;
EXIT;

Descarga Drupal

Primero, deberá descargar la última versión de Drupal desde su sitio web oficial.

Instale wget si aún no está instalado:

sudo dnf install wget

Descarga Drupal con el siguiente comando:

sudo wget https://ftp.drupal.org/files/projects/drupal-8.7.10.tar.gz

Instale tar si aún no está instalado:

sudo dnf install tar

Una vez descargado Drupal, extrae el archivo con el siguiente comando:

sudo tar -xvzf drupal-8.7.10.tar.gz

Luego, mueva el directorio extraído al directorio raíz web de Nginx con el siguiente comando:

sudo mv drupal-8.7.10 /var/www/html/drupal

Luego, cree un directorio para almacenar los archivos del sitio web y cambie el nombre del default.settings.php como se muestra a continuación:

sudo mkdir /var/www/html/drupal/sites/default/files
sudo cp /var/www/html/drupal/sites/default/default.settings.php /var/www/html/drupal/sites/default/settings.php

A continuación, cambie la propiedad del directorio Drupal a nginx como se muestra a continuación:

sudo chown -R nginx:nginx /var/www/html/drupal/

Configurar Nginx para Drupal

Primero, cree un archivo de configuración php-fpm para Drupal con el siguiente comando:

sudo vi /etc/php-fpm.d/drupal.conf

Agrega las siguientes líneas:

[drupal]
 user = nginx
 group = nginx
 listen.owner = nginx
 listen.group = nginx
 listen = /run/php-fpm/drupal.sock
 pm = ondemand
 pm.max_children = 50
 pm.process_idle_timeout = 10s
 pm.max_requests = 500
 chdir = /

Guarde y cierre el archivo cuando termine. Luego, cree un archivo de configuración de host virtual Nginx para Drupal:

sudo vi /etc/nginx/conf.d/drupal.conf

Agrega las siguientes líneas:

server {
 listen 80;
 server_name example.com;

 root /var/www/html/drupal;

 access_log /var/log/nginx/example.com.access.log;
 error_log /var/log/nginx/example.com.error.log;

 location = /favicon.ico {
 log_not_found off;
 access_log off;
 }

 location = /robots.txt {
 allow all;
 log_not_found off;
 access_log off;
 }

 location ~ \..*/.*\.php$ {
 return 403;
 }

 location ~ ^/sites/.*/private/{
 return 403;
 }

 # Block access to scripts in site files directory
 location ~ ^/sites/[^/]+/files/.*\.php$ {
 deny all;
 }
 location ~ (^|/)\. {
 return 403;
 }

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

 location @rewrite {
 rewrite ^/(.*)$ /index.php?q=$1;
 }
 location ~ /vendor/.*\.php$ {
 deny all;
 return 404;
 }


 location ~ '\.php$|^/update.php' {
 fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
 include fastcgi_params;
 # Block httpoxy attacks. See https://httpoxy.org/.
 fastcgi_param HTTP_PROXY "";
 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
 fastcgi_param PATH_INFO $fastcgi_path_info;
 fastcgi_param QUERY_STRING $query_string;
 fastcgi_intercept_errors on;
 fastcgi_pass unix:/run/php-fpm/drupal.sock;
 }
 location ~ ^/sites/.*/files/styles/{ # For Drupal >= 7
 try_files $uri @rewrite;
 }

 # Handle private files through Drupal. Private file's path can come
 # with a language prefix.
 location ~ ^(/[az\-]+)?/system/files/{ # For Drupal >= 7
 try_files $uri /index.php?$query_string;
 }

 location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
 try_files $uri @rewrite;
 expires max;
 log_not_found off;
 }
 }

Guarde y cierre el archivo. Luego, reinicie php-fpm y el servicio Nginx para aplicar los cambios:

sudo systemctl restart php-fpm
sudo systemctl restart nginx

Configurar el cortafuegos

Si tiene el firewall habilitado, deberá crear una regla de firewall para permitir el servicio HTTP y HTTPS desde redes externas. Puede permitir esto con el siguiente comando:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https firewall-cmd --reload
sudo firewall-cmd --reload

Configurar HTTPS con Let's Encrypt SSL

Drupal ahora está instalado y configurado. Es hora de protegerlo con Let's Encrypt SSL gratuito.

Para hacer esto, necesitará descargar el cliente certbot en su servidor. Puede descargar y establecer los permisos correctos ejecutando el siguiente comando:

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

Ahora, ejecute el siguiente comando para obtener e instalar un certificado SSL para su sitio web Drupal.

sudo certbot-auto --nginx -d example.com

El comando anterior instalará primero todas las dependencias requeridas en su servidor. Una vez instalado, se le pedirá que proporcione una dirección de correo electrónico y que acepte el plazo de servicio como se muestra a continuación:

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 example.com
 Waiting for verification...
 Cleaning up challenges
 Deploying Certificate to VirtualHost /etc/nginx/conf.d/drupal.conf

A continuación, deberá elegir si desea redirigir el tráfico HTTP a través de 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

Escriba 2 y presione Entrar para continuar. Una vez finalizada la instalación, debería ver el siguiente resultado:

Redirecting all traffic on port 80 to ssl in /etc/nginx/conf.d/drupal.conf

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

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

 IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
 /etc/letsencrypt/live/example.com/fullchain.pem
 Your key file has been saved at:
 /etc/letsencrypt/live/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

Inicie sesión en el sitio web de Drupal

Ahora abra su navegador web y escriba la URL https://example.com. Serás redirigido a la página de instalación de Drupal.

Seleccione el idioma deseado y haga clic en el botón Guardar y continuar.

Elija su perfil de instalación y haga clic en el botón Guardar y continuar.

Proporcione los detalles de la base de datos y haga clic en el botón Guardar y continuar.

Proporcione su nombre de sitio, nombre de usuario de administrador, contraseña y haga clic en el botón Guardar y continuar. Debería ver el panel de Drupal.

Conclusión

En este tutorial hemos visto cómo instalar y asegurar Drupal en el servidor CentOS 8.

Buy me a coffeeBuy me a coffee

Supportaci se ti piacciono i nostri contenuti. Grazie.

Successivamente, completa il checkout per l'accesso completo a Noviello.it.
Bentornato! Accesso eseguito correttamente.
Ti sei abbonato con successo a Noviello.it.
Successo! Il tuo account è completamente attivato, ora hai accesso a tutti i contenuti.
Operazione riuscita. Le tue informazioni di fatturazione sono state aggiornate.
La tua fatturazione non è stata aggiornata.