Установите и настройте Drupal 8 с Nginx и Lets Encrypt на CentOS 8
На этой странице
- Требования
- Установите Nginx, MariaDB и PHP.
- Настроить базу данных
- Загрузить Drupal
- Настройка Nginx для Drupal
- Настройка SELinux и брандмауэра
- Защитите Drupal с помощью Lets Encrypt SSL
- Доступ к веб-сайту Drupal
Drupal — это бесплатная масштабируемая система управления контентом с открытым исходным кодом, которую могут использовать люди для создания и управления любыми типами веб-сайтов. Он написан на PHP и использует MySQL/MariaDB для хранения своих данных. Drupal предоставляет богатый набор функций, которые можно расширить за счет тысяч надстроек. Drupal поддерживает множество веб-серверов, включая Apache, Nginx, IIS, Lighttpd и базы данных MySQL, MariaDB, MongoDB, SQLite, PostgreSQL и сервер MS SQL. Drupal поставляется с простым и удобным веб-интерфейсом, который позволяет создавать веб-сайты без каких-либо знаний в области программирования.
В этом руководстве мы покажем вам, как установить Drupal 8 на сервер CentOS 8 и защитить его с помощью бесплатного SSL от Lets Encrypt.
Требования
- Сервер под управлением CentOS 8.
- Действительное доменное имя, указанное с IP-адресом вашего сервера.
- На сервере настроен пароль root.
Установите Nginx, MariaDB и PHP
Прежде чем начать, вам нужно будет установить сервер LEMP на свой сервер. Вы можете установить его, выполнив следующую команду:
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
После установки запустите службы Nginx, MariaDB и php-fpm и включите их после перезагрузки системы с помощью следующей команды:
systemctl start nginx
systemctl start php-fpm
systemctl start mariadb
systemctl enable nginx
systemctl enable php-fpm
systemctl enable mariadb
Настроить базу данных
По умолчанию MariaDB не защищена, поэтому вам необходимо ее защитить. Вы можете защитить его, выполнив следующую команду:
mysql_secure_installation
Ответьте на все вопросы, как показано ниже:
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
Когда вы закончите, войдите в оболочку MariaDB с помощью следующей команды:
mysql -u root -p
При появлении запроса укажите свой пароль root, затем создайте базу данных и пользователя для Drupal с помощью следующей команды:
MariaDB [(none)]> CREATE DATABASE drupaldb CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
MariaDB [(none)]> CREATE USER IDENTIFIED BY "password";
Затем предоставьте все привилегии drupaldb с помощью следующей команды:
MariaDB [(none)]> GRANT ALL ON drupaldb.* TO IDENTIFIED BY "password";
Затем сбросьте привилегии и выйдите из оболочки MariaDB с помощью следующей команды:
MariaDB [(none)]> FLUSH PRIVILEGES;
MariaDB [(none)]> EXIT;
Скачать Друпал
Во-первых, вам нужно будет загрузить последнюю версию Drupal с их официального сайта. Вы можете скачать его с помощью следующей команды:
wget https://ftp.drupal.org/files/projects/drupal-8.7.10.tar.gz
После загрузки извлеките загруженный файл с помощью следующей команды:
tar -xvzf drupal-8.7.10.tar.gz
Затем переместите извлеченный каталог в корневой веб-каталог Nginx с помощью следующей команды:
mv drupal-8.7.10 /var/www/html/drupal
Затем создайте каталог для хранения файлов веб-сайта и переименуйте файл default.settings.php, как показано ниже:
mkdir /var/www/html/drupal/sites/default/files
cp /var/www/html/drupal/sites/default/default.settings.php /var/www/html/drupal/sites/default/settings.php
Затем измените владельца каталога Drupal на nginx, как показано ниже:
chown -R nginx:nginx /var/www/html/drupal/
Настроить Nginx для Drupal
Сначала создайте файл конфигурации php-fpm для Drupal с помощью следующей команды:
nano /etc/php-fpm.d/drupal.conf
Добавьте следующие строки:
[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 = /
Сохраните и закройте файл, когда закончите. Затем создайте файл конфигурации виртуального хоста Nginx для Drupal:
nano /etc/nginx/conf.d/drupal.conf
Добавьте следующие строки:
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 ~ ^(/[a-z\-]+)?/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; } }
Сохраните и закройте файл. Затем перезапустите службу php-fpm и Nginx, чтобы изменения вступили в силу:
systemctl restart php-fpm
systemctl restart nginx
Настройте SELinux и брандмауэр
По умолчанию SELinux включен в CentOS 8. Поэтому вам нужно будет настроить SELinux для правильной работы Drupal.
Во-первых, позволяет Drupal записывать в общедоступные и частные каталоги файлов с помощью следующей команды:
semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/html/drupal(/.*)?"
semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/drupal/sites/default/settings.php'
semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/drupal/sites/default/files'
restorecon -Rv /var/www/html/drupal
restorecon -v /var/www/html/drupal/sites/default/settings.php
restorecon -Rv /var/www/html/drupal/sites/default/files
Затем позволяет Drupal отправлять исходящие электронные письма с помощью следующей команды:
setsebool -P httpd_can_sendmail on
Затем вам нужно будет создать правило брандмауэра, чтобы разрешить службы HTTP и HTTPS из внешних сетей. Вы можете разрешить это с помощью следующей команды:
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
Безопасный Drupal с Lets Encrypt SSL
Drupal установлен и настроен. Пришло время защитить его с помощью бесплатного SSL от Lets Encrypt.
Для этого вам нужно будет загрузить клиент certbot на свой сервер. Вы можете загрузить и установить правильное разрешение, выполнив следующую команду:
wget https://dl.eff.org/certbot-auto
mv certbot-auto /usr/local/bin/certbot-auto
chown root /usr/local/bin/certbot-auto
chmod 0755 /usr/local/bin/certbot-auto
Теперь выполните следующую команду, чтобы получить и установить SSL-сертификат для вашего веб-сайта Drupal.
certbot-auto --nginx -d example.com
Приведенная выше команда сначала установит все необходимые зависимости на ваш сервер. После установки вам будет предложено указать адрес электронной почты и принять условия обслуживания, как показано ниже:
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): - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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
Затем вам нужно будет выбрать, следует ли перенаправлять 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/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
Доступ к веб-сайту Drupal
Теперь откройте веб-браузер и введите URL-адрес https://example.com. Вы будете перенаправлены на следующую страницу:
Выберите нужный язык и нажмите кнопку «Сохранить и продолжить». Вы должны увидеть следующую страницу:
Выберите профиль установки и нажмите кнопку «Сохранить и продолжить». Вы должны увидеть следующую страницу:
Укажите данные своей базы данных и нажмите кнопку «Сохранить и продолжить». Вы должны увидеть следующую страницу:
Укажите имя вашего сайта, имя пользователя администратора, пароль и нажмите кнопку «Сохранить и продолжить». Вы должны увидеть панель инструментов Drupal на следующей странице:
Поздравляем! вы успешно установили и защитили Drupal на сервере CentOS 8.