Как установить Laravel PHP Framework с Nginx и Free Lets Encrypt SSL на AlmaLinux 8
На этой странице
- Предпосылки
- Установить сервер LEMP
- Установить Композитор
- Установите Laravel на Alma Linux 8
- Создание виртуального хоста Nginx для Laravel
- Настройка брандмауэра для Laravel
- Доступ к веб-интерфейсу Laravel
- Включить SSL на веб-сайте Laravel
- Заключение
Laravel — это бесплатная легкая веб-инфраструктура PHP с открытым исходным кодом, используемая для создания веб-приложений на основе PHP. Он популярен благодаря элегантному синтаксису, расширенным функциям и надежному набору инструментов. Он основан на фреймворке Symfony и помогает разработчикам упростить разработку веб-приложений. Он также предоставляет интерфейс командной строки Artisan для выполнения операций для ваших приложений. Он предлагает мощные функции, включая Artisan, архитектуру MVC, объектно-реляционное сопоставление, механизм шаблонов, модульное тестирование и систему миграции баз данных.
В этом посте мы покажем вам, как установить Laravel с Nginx на Alma Linux 8.
Предпосылки
- Сервер под управлением Alma Linux 8.
- Действительное доменное имя, указанное с IP-адресом вашего сервера.
- На вашем сервере настроен пароль root.
Установить LEMP-сервер
Во-первых, вам нужно будет установить на свой сервер Nginx, MariaDB, PHP и другие необходимые расширения PHP. Вы можете установить их все, выполнив следующую команду:
dnf install nginx mariadb-server php php-fpm php-common php-xml php-mbstring php-json php-zip php-mysqlnd curl unzip -y
После установки всех пакетов отредактируйте файл конфигурации php-fpm и настройте его для использования Nginx:
nano /etc/php-fpm.d/www.conf
Измените следующие строки:
listen.owner = nginx listen.group = nginx
Сохраните и закройте файл, затем отредактируйте файл конфигурации PHP и измените значения по умолчанию:
nano /etc/php.ini
Измените следующие строки:
date.timezone = Asia/Kolkata cgi.fix_pathinfo=1
Сохраните и закройте файл, затем запустите и включите службу Nginx, MariaDB и PHP-FPM с помощью следующей команды:
systemctl start nginx
systemctl start mariadb
systemctl start php-fpm
systemctl enable nginx
systemctl enable mariadb
systemctl enable php-fpm
Как только вы закончите, вы можете перейти к следующему шагу.
Установить Композитор
В этом посте мы установим Laravel с помощью Composer. Поэтому вам нужно будет установить Composer в вашей системе. Вы можете установить его, выполнив следующую команду:
curl -sS https://getcomposer.org/installer | php
Вы получите следующий вывод:
All settings correct for using Composer Downloading... Composer (version 2.2.3) successfully installed to: /root/composer.phar Use it: php composer.phar
Затем переместите двоичный файл Composer на системный путь и установите соответствующие разрешения с помощью следующей команды:
mv composer.phar /usr/local/bin/composer
chmod +x /usr/local/bin/composer
Затем проверьте версию Composer с помощью следующей команды:
composer --version
Вы получите следующий вывод:
Composer version 2.2.3 2021-12-31 12:18:53
Установите Laravel на Alma Linux 8
Затем измените каталог на корневой веб-каталог Nginx и установите Laravel с помощью Composer:
cd /var/www/html/
composer create-project --prefer-dist laravel/laravel laravel
Вы получите следующий вывод:
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.
Затем установите правильное право собственности и разрешения для 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/
Как только вы закончите, вы можете перейти к следующему шагу.
Создайте виртуальный хост Nginx для Laravel
Далее вам нужно будет создать файл конфигурации Nginx для Laravel. Вы можете создать его с помощью следующей команды:
nano /etc/nginx/conf.d/laravel.conf
Добавьте следующие строки:
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; } }
Сохраните и закройте файл, затем проверьте Laravel на наличие ошибок конфигурации:
nginx -t
Вы должны получить следующий результат:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Затем перезапустите службу Nginx и PHP-FPM, чтобы изменения вступили в силу:
systemctl restart php-fpm
systemctl restart nginx
Вы также можете проверить статус Nginx с помощью следующей команды:
systemctl status nginx
Вы получите следующий вывод:
? 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.
Настроить брандмауэр для Laravel
Далее вам нужно будет разрешить порты 80 и 443 через межсетевой экран firewalld. Вы можете разрешить их с помощью следующей команды:
firewall-cmd --zone=public --permanent --add-service=http
firewall-cmd --zone=public --permanent --add-service=https
Затем перезагрузите firewalld, чтобы применить изменения:
firewall-cmd --reload
Доступ к веб-интерфейсу Laravel
Теперь откройте веб-браузер и войдите в веб-интерфейс Laravel, используя URL-адрес http://laravel.exampledomain.com. Вы должны увидеть страницу Laravel по умолчанию на следующем экране:
Включить SSL на веб-сайте Laravel
Рекомендуется включить SSL на веб-сайте Laravel для защиты соединения. Lets Encrypt предоставляет бесплатный SSL для получения, обновления и управления сертификатами SSL/TLS для вашего домена. Сначала установите клиент Certbot с помощью следующей команды:
dnf install epel-release -y
dnf install certbot -y
Затем выполните следующую команду, чтобы загрузить Lets Encrypt SSL для вашего домена Laravel:
certbot --nginx -d laravel.exampledomain.com
Вам будет предложено указать действующий адрес электронной почты и принять условия обслуживания, как показано ниже:
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): - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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
Затем выберите, следует ли перенаправлять HTTP-трафик на 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
Введите 2 и нажмите Enter, чтобы начать процесс. После установки сертификата вы должны увидеть следующий вывод:
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.
На данный момент ваш сайт Laravel защищен с помощью Lets Encrypt SSL. Теперь вы можете получить к нему безопасный доступ, используя URL-адрес https://laravel.exampledomain.com.
Заключение
Поздравляем! вы успешно установили Laravel с Nginx и Lets Encrypt SSL на Alma Linux 8. Теперь вы можете приступить к разработке приложений на основе PHP с использованием фреймворка Laravel. Не стесняйтесь спрашивать меня, если у вас есть какие-либо вопросы.