Cómo instalar Laravel PHP Framework con Nginx y Let’s Encrypt SSL gratis en AlmaLinux 8

Laravel

Laravel es un framework web PHP gratuito, de código abierto y ligero utilizado para la construcción de aplicaciones web basadas en PHP. Es popular debido a su elegante sintaxis, características avanzadas, y un conjunto de herramientas robustas. Está basado en el framework Symfony y ayuda a los desarrolladores a simplificar el desarrollo de aplicaciones web. También proporciona una interfaz de línea de comandos Artisan para realizar operaciones para sus aplicaciones. Ofrece potentes características que incluyen, Artisan, arquitectura MVC, mapeo objeto-relacional, motor de plantillas, pruebas unitarias y sistema de migración de bases de datos.

En este post, le mostraremos cómo instalar Laravel con Nginx en Alma Linux 8.

Requisitos previos

  • Un servidor con Alma Linux 8.
  • Un nombre de dominio válido apuntado con la IP de su servidor.
  • Se ha configurado una contraseña de root en su servidor.

Instalar el servidor LEMP

En primer lugar, necesitará instalar Nginx, MariaDB, PHP y otras extensiones PHP necesarias en su servidor. Puedes instalarlos todos ejecutando el siguiente comando:

dnf install nginx mariadb-server php php-fpm php-common php-xml php-mbstring php-json php-zip php-mysqlnd curl unzip -y

Después de instalar todos los paquetes, edita el archivo de configuración de php-fpm y configúralo para usar Nginx:

nano /etc/php-fpm.d/www.conf

Cambia las siguientes líneas:

listen.owner = nginx
listen.group = nginx

Guarde y cierre el archivo y luego edite el archivo de configuración de PHP y cambie los valores por defecto:

nano /etc/php.ini

Cambie las siguientes líneas:

date.timezone = Asia/Kolkata
cgi.fix_pathinfo=1

Guarde y cierre el archivo y luego inicie y habilite el servicio Nginx, MariaDB y PHP-FPM usando el siguiente comando:

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

Una vez que haya terminado, puede proceder al siguiente paso.

Instalar Composer

En este post, vamos a instalar Laravel utilizando el Composer. Así que necesitarás instalar el Composer en tu sistema. Puedes instalarlo ejecutando el siguiente comando:

curl -sS https://getcomposer.org/installer | php

Obtendrá la siguiente salida:

All settings correct for using Composer
Downloading...

Composer (version 2.2.3) successfully installed to: /root/composer.phar
Use it: php composer.phar

A continuación, mueva el binario de Composer a la ruta del sistema y establezca el permiso adecuado con el siguiente comando:

mv composer.phar /usr/local/bin/composer
chmod +x /usr/local/bin/composer

A continuación, verifique la versión de Composer con el siguiente comando:

composer --version

Obtendrá la siguiente salida:

Composer version 2.2.3 2021-12-31 12:18:53

Instalar Laravel en Alma Linux 8

A continuación, cambie el directorio al directorio raíz de la web Nginx e instale el Laravel utilizando el Compositor:

cd /var/www/html/
composer create-project --prefer-dist laravel/laravel laravel

Obtendrás la siguiente salida:

Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: fruitcake/laravel-cors
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.
69 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
> @php artisan key:generate --ansi
Application key set successfully.

A continuación, establezca la propiedad y los permisos adecuados para Laravel:

chown -R nginx:nginx /var/www/html/laravel/
chown -R nginx:nginx /var/www/html/laravel/storage/
chown -R nginx:nginx /var/www/html/laravel/bootstrap/cache/
chmod -R 0777 /var/www/html/laravel/storage/
chmod -R 0775 /var/www/html/laravel/bootstrap/cache/

Una vez que haya terminado, puede proceder al siguiente paso.

Crear un host virtual Nginx para Laravel

A continuación, tendrá que crear un archivo de configuración de Nginx para Laravel. Puedes crearlo usando el siguiente comando:

nano /etc/nginx/conf.d/laravel.conf

Añade las siguientes líneas:Anuncio

server {
       listen 80;
       server_name laravel.exampledomain.com;
       root        /var/www/html/laravel/public;
       index       index.php;
       charset utf-8;
       gzip on;
	gzip_types text/css application/javascript text/javascript application/x-javascript  image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon;
        location / {
        	try_files $uri $uri/ /index.php?$query_string;
        }

        location ~ \.php {
                include fastcgi.conf;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass unix:/run/php-fpm/www.sock;
        }
        location ~ /\.ht {
                deny all;
        }
}

Guarde y cierre el archivo y luego verifique el Laravel para cualquier error de configuración:

nginx -t

Debería 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

A continuación, reinicie el servicio Nginx y PHP-FPM para aplicar los cambios:

systemctl restart php-fpm
systemctl restart nginx

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

systemctl status nginx

Obtendrás la siguiente salida:

? nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
  Drop-In: /usr/lib/systemd/system/nginx.service.d
           ??php-fpm.conf
   Active: active (running) since Fri 2022-01-07 08:29:11 UTC; 4s ago
  Process: 8186 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS)
  Process: 8184 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=0/SUCCESS)
  Process: 8182 ExecStartPre=/usr/bin/rm -f /run/nginx.pid (code=exited, status=0/SUCCESS)
 Main PID: 8188 (nginx)
    Tasks: 2 (limit: 11411)
   Memory: 3.7M
   CGroup: /system.slice/nginx.service
           ??8188 nginx: master process /usr/sbin/nginx
           ??8189 nginx: worker process

Jan 07 08:29:11 linux systemd[1]: nginx.service: Succeeded.
Jan 07 08:29:11 linux systemd[1]: Stopped The nginx HTTP and reverse proxy server.
Jan 07 08:29:11 linux systemd[1]: Starting The nginx HTTP and reverse proxy server...
Jan 07 08:29:11 linux nginx[8184]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
Jan 07 08:29:11 linux nginx[8184]: nginx: configuration file /etc/nginx/nginx.conf test is successful
Jan 07 08:29:11 linux systemd[1]: nginx.service: Failed to parse PID from file /run/nginx.pid: Invalid argument
Jan 07 08:29:11 linux systemd[1]: Started The nginx HTTP and reverse proxy server.

Configurar el Firewall para Laravel

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

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

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

firewall-cmd --reload

Acceda a la interfaz web de Laravel

Ahora, abra su navegador web y acceda a la interfaz web de Laravel utilizando la URL http://laravel.exampledomain.com. Debería ver la página por defecto de Laravel en la siguiente pantalla:

Laravel

Habilitar SSL en el sitio web de Laravel

Se recomienda habilitar el SSL en el sitio web de Laravel para asegurar la conexión. Let’s Encrypt proporciona un SSL gratuito para obtener, renovar y gestionar certificados SSL/TLS para tu dominio. Primero, instala el cliente Certbot con el siguiente comando:

dnf install epel-release -y
dnf install certbot -y

A continuación, ejecute el siguiente comando para descargar Let’s Encrypt SSL para su dominio Laravel:

certbot --nginx -d laravel.exampledomain.com

Se le pedirá que proporcione su correo electrónico válido y que acepte 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 laravel.exampledomain.com
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/nginx/conf.d/laravel.conf

A continuación, seleccione si desea 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

Escriba 2 y pulse Intro para iniciar el proceso. Una vez instalado el certificado, debería ver la siguiente salida:

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

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

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

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/laravel.exampledomain.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/laravel.exampledomain.com/privkey.pem
   Your cert will expire on 2022-04-11. 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"
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.
 - 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

 - We were unable to subscribe you the EFF mailing list because your
   e-mail address appears to be invalid. You can try again later by
   visiting https://act.eff.org.

En este punto, su sitio web Laravel está asegurado con Let’s Encrypt SSL. Ahora puedes acceder a él de forma segura usando la URL https://laravel.exampledomain.comAnuncio publicitario

Conclusión

Enhorabuena! has instalado con éxito Laravel con Nginx y Let’s Encrypt SSL en Alma Linux 8. ahora puedes empezar a desarrollar aplicaciones basadas en PHP utilizando el framework Laravel. No dudes en preguntarme si tienes alguna duda.

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *