Cómo instalar Laravel PHP Framework con Nginx en Ubuntu 22.04

Laravel es un framework web PHP gratuito y de código abierto creado por Taylor Otwell. Está basado en Symfony y sigue el patrón arquitectónico modelo-vista-controlador. Está diseñado para construir aplicaciones web de alto nivel utilizando sus significativas y elegantes sintaxis. Tiene muchas funciones integradas que facilitan y agilizan el desarrollo de aplicaciones web. Laravel ganó más popularidad tras el lanzamiento de la versión 3, que incluye prácticas funciones, como la línea de comandos Artisan y la base de datos de soporte, e introdujo un sistema de empaquetado llamado bundles.

Este tutorial te mostrará cómo instalar Laravel PHP Framework con el servidor web Nginx en Ubuntu 22.04.

Requisitos previos

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

Instalar el servidor LEMP

Antes de empezar, tendrás que instalar en tu servidor el servidor web Nginx, el sistema de base de datos MariaDB, PHP y otras dependencias necesarias. Puedes instalarlos todos ejecutando el siguiente comando:

apt install -y nginx mariadb-server php php-fpm php-common php-cli php-gd php-mysqlnd php-curl php-intl php-mbstring php-bcmath php-xml php-zip wget git

Una vez instalados todos los paquetes, verifica la versión de PHP mediante el siguiente comando:

php -v

Deberías ver la siguiente salida:

PHP 8.1.2 (cli) (built: Apr  7 2022 17:46:26) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.2, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.2, Copyright (c), by Zend Technologies

Instalar PHP Composer

Composer es un gestor de dependencias para PHP que se utiliza para gestionar las dependencias de PHP. Para instalar el Composer, necesitarás instalar el paquete curl en tu servidor.

apt install -y curl

A continuación, instala PHP Composer utilizando el siguiente comando:

curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/bin --filename=composer

Una vez instalado Composer, obtendrás la siguiente salida:

All settings correct for using Composer
Downloading...

Composer (version 2.3.5) successfully installed to: /usr/bin/composer
Use it: php /usr/bin/composer

A continuación, verifica la versión de Composer utilizando el siguiente comando:

composer --version

Deberías obtener la siguiente salida:

Composer version 2.3.5 2022-04-13 16:43:00

Instalar Laravel en Ubuntu 22.04

En primer lugar, navega hasta el directorio raíz web de Nginx y descarga la última versión de Laravel utilizando el comando Composer:

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

Obtendrás la siguiente salida:

55 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: laravel/sail
Discovered Package: laravel/sanctum
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Discovered Package: spatie/laravel-ignition
Package manifest generated successfully.
78 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
> @php artisan vendor:publish --tag=laravel-assets --ansi --force
No publishable resources for tag [laravel-assets].
Publishing complete.
> @php artisan key:generate --ansi
Application key set successfully.

A continuación, cambia el directorio al Laravel y ejecuta el Laravel utilizando el siguiente comando:

cd laravel
php artisan serve --host 0.0.0.0 --port 8000

Si todo va bien, deberías obtener la siguiente salida:

Starting Laravel development server: http://0.0.0.0:8000
[Sun May 22 08:17:45 2022] PHP 8.1.2 Development Server (http://0.0.0.0:8000) started

Pulsa CTRL+C para detener el Laravel. A continuación, cambia la propiedad y el permiso del Laravel:

chown -R www-data:www-data /var/www/html/laravel
chmod -R 0777 /var/www/html/laravel

Configurar Nginx para Laravel

A continuación, crea un archivo de configuración de host virtual Nginx para Laravel utilizando el siguiente comando:

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

Añade las siguientes líneas:

server {
    listen 80;
    server_name laravel.example.com;
    root /var/www/html/laravel/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    charset utf-8;

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

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

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

Guarda y cierra el archivo cuando hayas terminado, luego verifica que Nginx no tenga ningún error de sintaxis utilizando el siguiente comando:

nginx -t

Obtendrás 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, reinicia el servicio Nginx y PHP-FPM para aplicar los cambios:

systemctl restart php8.1-fpm nginx

También puedes comprobar el estado del Nginx utilizando 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-05-22 08:19:20 UTC; 17s ago
       Docs: man:nginx(8)
    Process: 16865 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
    Process: 16866 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
   Main PID: 16867 (nginx)
      Tasks: 2 (limit: 2292)
     Memory: 2.6M
        CPU: 33ms
     CGroup: /system.slice/nginx.service
             ??16867 "nginx: master process /usr/sbin/nginx -g daemon on; master_process on;"
             ??16868 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""

May 22 08:19:20 ubuntu2204 systemd[1]: Starting A high performance web server and a reverse proxy server...
May 22 08:19:20 ubuntu2204 systemd[1]: Started A high performance web server and a reverse proxy server.

Acceder a la interfaz web de Laravel

En este punto, Laravel está instalado y configurado con Nginx. Ahora puedes acceder a la interfaz web de Laravel utilizando la URL http://laravel.example.com. Deberías ver el Dashboard de Laravel en la siguiente página:

Asegura Laravel con Let’s Encrypt

A continuación, tendrás que instalar el paquete cliente Certbot para instalar y gestionar el SSL Let’s Encrypt.

Primero, instala el Certbot con el siguiente comando:

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

Una vez finalizada la instalación, ejecuta el siguiente comando para instalar el SSL de Let’s Encrypt en tu sitio web:

certbot --nginx -d laravel.example.com

Se te pedirá que proporciones una dirección de correo electrónico válida y que 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 laravel.example.com
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/nginx/conf.d/laravel.conf

A continuación, elige si deseas o no redirigir el tráfico HTTP a HTTPS, como se muestra a continuación:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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. Deberías ver el siguiente resultado:

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

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

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

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/laravel.example.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/laravel.example.com/privkey.pem
   Your cert will expire on 2022-08-22. 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.

Conclusión

¡Enhorabuena! Has instalado correctamente Laravel con Nginx en Ubuntu 22.04. Ahora puedes empezar a desarrollar aplicaciones PHP de alto rendimiento utilizando el framework Laravel. No dudes en preguntarme si tienes alguna duda.

También te podría gustar...