Поиск по сайту:

Как установить Grav CMS с Nginx на Ubuntu 20.04


Это руководство существует для этих версий ОС

  • Ubuntu 20.04 (Focal Fossa)
  • Ubuntu 18.04 (Bionic Beaver)

На этой странице

  1. Предпосылки
  2. Начало работы
  3. Установите Nginx и PHP
  4. Установите Grav CMS
  5. Настройка Nginx для Grav CMS
  6. Доступ к CMS Grav
  7. Защита Grav CMS с помощью Lets Encrypt SSL
  8. Заключение

Grav — это бесплатная CMS с открытым исходным кодом и плоской файловой системой, которая не требует какой-либо базы данных. Он основан на PHP и предлагает несколько функций, которые могут быть недоступны в других CMS, таких как WordPress, Joomla и т. д. Он прост, удобен в использовании и поставляется с некоторыми ключевыми технологиями, включая шаблоны Twig, Markdown, YAML, Parsedown, Doctrine Cache, Gregwar Image Library и Symfony Console.

В этом руководстве я покажу вам, как установить Grav CMS с Nginx и Lets Encrypt SSL на сервере Ubuntu 20.04.

Предпосылки

  • Сервер под управлением Ubuntu 20.04.
  • Действительное доменное имя, указанное с IP-адресом вашего сервера.
  • На сервере настроен пароль root.

Начиная

Сначала обновите системные пакеты до обновленной версии, выполнив следующую команду:

apt-get update -y

Как только все пакеты будут обновлены, вы можете перейти к следующему шагу.

Установите Nginx и PHP

Во-первых, вам нужно будет установить веб-сервер Nginx, PHP и другие расширения PHP в вашей системе. Вы можете установить их все с помощью следующей команды:

apt-get install nginx php php-cli php-fpm php-common php-curl php-gd php-json php-mbstring php-xml php-zip php-opcache php-apcu unzip -y

После установки всех пакетов проверьте версию PHP с помощью следующей команды:

php --version

Вы должны получить следующий результат:

PHP 7.4.3 (cli) (built: Jul  5 2021 15:13:35) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.3, Copyright (c), by Zend Technologies

Затем отредактируйте файл php.ini и внесите некоторые изменения:

nano /etc/php/7.4/fpm/php.ini

Измените следующие строки:

memory_limit = 256M
upload_max_filesize = 100M
max_execution_time = 360
max_input_vars = 1500
date.timezone = America/Chicago

Сохраните и закройте файл, затем перезапустите службу PHP-FPM, чтобы применить изменения:

systemctl restart php7.4-fpm

Как только вы закончите, вы можете перейти к следующему шагу.

Установить CMS Грав

Затем вам нужно будет загрузить Grav CMS в корневой веб-каталог Nginx. Вы можете загрузить его со страницы загрузки Grav, используя следующую команду:

cd /var/www/html
wget https://getgrav.org/download/core/grav-admin/1.7.17

После завершения загрузки разархивируйте загруженный файл с помощью следующей команды:

unzip 1.7.17

Затем переименуйте извлеченный каталог в grav с помощью следующей команды:

mv grav-admin grav

Затем установите правильное право собственности на каталог grav:

chown -R www-data:www-data /var/www/html/grav

Как только вы закончите, вы можете перейти к следующему шагу.

Настройка Nginx для Grav CMS

Затем вам нужно будет создать файл конфигурации виртуального хоста Nginx для размещения Grav CMS. Вы можете создать его с помощью следующей команды:

nano /etc/nginx/conf.d/grav.conf

Добавьте следующие строки:

server {

listen 80;

server_name grav.example.com;
root /var/www/html/grav;

index index.html index.php;

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

   location ~* /(\.git|cache|bin|logs|backup|tests)/.*$ { return 403; }
   location ~* /(system|vendor)/.*\.(txt|xml|md|html|yaml|yml|php|pl|py|cgi|twig|sh|bat)$ { return 403; }
   location ~* /user/.*\.(txt|md|yaml|yml|php|pl|py|cgi|twig|sh|bat)$ { return 403; }
   location ~ /(LICENSE\.txt|composer\.lock|composer\.json|nginx\.conf|web\.config|htaccess\.txt|\.htaccess) { return 403; }

location ~ \.php$ {
   fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
   fastcgi_split_path_info ^(.+\.php)(/.+)$;
   fastcgi_index index.php;
   include fastcgi_params;
   fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
 }

}

Сохраните и закройте файл, когда закончите, затем проверьте Nginx на наличие синтаксической ошибки:

nginx -t

Вы должны получить следующий результат:

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

Наконец, перезапустите службу Nginx, чтобы применить изменения:

systemctl restart nginx

Вы также можете проверить статус Nginx с помощью следующей команды:

systemctl status nginx

Вы должны увидеть следующий вывод:

? 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 Fri 2021-07-09 06:45:28 UTC; 3s ago
       Docs: man:nginx(8)
    Process: 33099 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
    Process: 33110 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
   Main PID: 33111 (nginx)
      Tasks: 2 (limit: 2353)
     Memory: 2.6M
     CGroup: /system.slice/nginx.service
             ??33111 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
             ??33112 nginx: worker process

Jul 09 06:45:28 node1 systemd[1]: Starting A high performance web server and a reverse proxy server...
Jul 09 06:45:28 node1 systemd[1]: Started A high performance web server and a reverse proxy server.

Когда все в порядке, можно переходить к следующему шагу.

Доступ к CMS Grav

Теперь вы можете получить доступ к веб-интерфейсу Grav CMS, используя URL-адрес http://grav.example.com. Вы должны увидеть следующий экран:

Задайте имя пользователя и пароль администратора и нажмите кнопку «Создать пользователя». Вы будете перенаправлены на панель инструментов Grav CMS:

Страница конфигурации

Страница учетных записей

Страница плагинов

Страница инструментов

Безопасная CMS Grav с Lets Encrypt SSL

Далее вам нужно будет установить клиентский пакет Certbot для установки и управления Lets Encrypt SSL.

Сначала установите Certbot с помощью следующей команды:

apt-get install python3-certbot-nginx -y

После завершения установки выполните следующую команду, чтобы установить Lets Encrypt SSL на свой веб-сайт:

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

Затем выберите, следует ли перенаправлять HTTP-трафик на HTTPS, как показано ниже:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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/grav.conf

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

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

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

Теперь вы можете безопасно получить доступ к Grav CMS, используя протокол HTTPS.

Заключение

Поздравляем! вы успешно установили Grav CMS с Nginx и Lets Encrypt SSL на сервере Ubuntu 20.04. Теперь вы можете легко создать свой веб-сайт с помощью Grav CMS.