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

Как установить Lighttpd с PHP и MariaDB на CentOS/RHEL 8/7


Lighthttpd — это безопасный, быстрый, гибкий и более оптимизированный веб-сервер с открытым исходным кодом, предназначенный для сред с критически важными скоростями и меньшим использованием памяти по сравнению с другими веб-серверами.

Он может обрабатывать до 10 000 подключений параллельно на одном сервере с эффективным управлением нагрузкой на ЦП и оснащен расширенным набором функций, такими как FastCGI, SCGI, аутентификация, сжатие вывода, перезапись URL-адресов и многие другие.

Lighthttpd — отличное решение для любого Linux-сервера благодаря своей высокоскоростной io-инфраструктуре, которая позволяет нам масштабировать производительность в несколько раз выше на том же оборудовании, чем на других альтернативных веб-серверах.

В этом руководстве мы объясним, как установить Lighthttpd с помощью PHP, PHP-FPM и MariaDB на PHP. Strong>Дистрибутивы CentOS/RHEL 8/7 с именем хоста linux-console.net и IP-адресом 192.168.0.103.

Шаг 1. Установите веб-сервер Lighttpd

1. Чтобы установить Lighthttpd, сначала необходимо обновить пакеты системного программного обеспечения и доступные репозитории, используя следующую команду yum.

yum -y update

2. Далее вам необходимо включить репозиторий EPEL в вашей системе и обновить пакеты программного обеспечения, используя следующие команды.

yum -y install epel-release
yum -y update

3. После включения репозитория EPEL вы можете установить Lighthttpd, выполнив следующую команду.

yum install lighttpd

4. После установки пакетов Lighthttpd вы можете запустить и включить автоматический запуск службы во время загрузки, а также обязательно проверить статус с помощью следующих команд.

systemctl start lighttpd
systemctl enable lighttpd
systemctl status lighttpd

5. Теперь проверьте версию Lighthttpd, установленную в вашей системе, с помощью следующей команды.

lighttpd -v

lighttpd/1.4.55 (ssl) - a light and fast webserver

6. Теперь вам нужно разрешить трафик HTTP и HTTPS на своем брандмауэре.

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

7. Теперь откройте браузер и перейдите по следующему URL-адресу, чтобы увидеть, как работает ваш веб-сервер Lighthttpd.

http://Your-Domain.com
OR
http://Your-IP-addr

Корневой каталог документов по умолчанию для Lighttpd — /var/www/lighttpd/, а основной файл конфигурации находится в /etc/lighttpd/lighttpd.conf.

Шаг 2. Установка MariaDB как MySQL в CentOS 7

8. Затем установите поддержку MySQL для Lighthttpd, используя следующие команды.

yum -y install mariadb mariadb-server

9. После завершения установки запустите, включите и проверьте состояние MariaDB, используя следующие команды.

systemctl start mariadb.service
systemctl enable mariadb.service
systemctl status mariadb.service

10. Наконец, вам нужно будет защитить установку MariaDB, введя следующую команду.

mysql_secure_installation

Вам будет предложено несколько различных вопросов относительно вашей установки MariaDB и того, как вы хотите ее защитить. Вы можете изменить пароль пользователя root базы данных, отключить тестовую базу данных, отключить анонимных пользователей и удаленно отключить вход root.

Пример вывода
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none): Enter OK, successfully used password, moving on... Setting the root password ensures that nobody can log into the MariaDB root user without the proper authorization. Set root password? [Y/n] y New password: Re-enter new password: Password updated successfully! Reloading privilege tables.. ... Success! By default, a MariaDB installation has an anonymous user, allowing anyone to log into MariaDB without having to have a user account created for them. This is intended only for testing, and to make the installation go a bit smoother. You should remove them before moving into a production environment. Remove anonymous users? [Y/n] y ... Success! Normally, root should only be allowed to connect from 'localhost'. This ensures that someone cannot guess at the root password from the network. Disallow root login remotely? [Y/n] y ... Success! By default, MariaDB comes with a database named 'test' that anyone can access. This is also intended only for testing and should be removed before moving into a production environment. Remove test database and access to it? [Y/n] y - Dropping test database... ... Success! - Removing privileges on test database... ... Success! Reloading the privilege tables will ensure that all changes made so far will take effect immediately. Reload privilege tables now? [Y/n] y ... Success! Cleaning up... All done! If you've completed all of the above steps, your MariaDB installation should now be secure. Thanks for using MariaDB!

11. Попробуйте подключиться к серверу MySQL и просмотреть существующие базы данных на вашем сервере баз данных с помощью следующих команд на терминале.

mysql -u root -p
Пример вывода
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 10
Server version: 5.5.60-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.00 sec)

MariaDB [(none)]>

Шаг 3. Установка PHP и PHP-FPM с FastCGI на CentOS 7

12. Чтобы включить PHP-FPM с поддержкой FastCGI, сначала необходимо установить PHP вместе с необходимыми расширениями. используя следующую команду.

yum -y install php php-mysqlnd php-pdo php-gd php-mbstring

13. После установки PHP включите поддержку PHP-FPM и FastCGI для Lighttpd. >, для этого вам необходимо установить и эти пакеты.

yum -y install php-fpm lighttpd-fastcgi

14. Теперь откройте файл с именем /etc/php-fpm.d/www.conf.

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

Установите для пользователя и группы значение Lighthttpd.

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
; RPM: apache Choosed to be able to access some dir as httpd
user = lighttpd
; RPM: Keep a group allowed to write in log dir.
group = lighttpd

Кроме того, PHP-FPM по умолчанию использует сокет /var/run/php/php7.0-fpm.sock, вам необходимо создать PHP-FPM использовать TCP-соединение. Придайте строке listen следующий вид:

;listen = /var/run/php/php7.0-fpm.sock
listen = 127.0.0.1:9000 

15. Теперь запустите службу PHP-FPM и убедитесь, что она автоматически запускается во время загрузки, используя следующие команды.

systemctl start php-fpm.service
systemctl enable php-fpm.service

Шаг 4. Включение PHP и PHP-FPM с помощью FastCGI в Lighttpd

16. Здесь нам нужно изменить три файла: /etc/php.ini, /etc/lighttpd/modules.conf и . /etc/lighttpd/conf.d/fastcgi.conf, чтобы включить поддержку PHP для Lightcgi.

Откройте первый файл /etc/php.ini.

vi /etc/php.ini

Раскомментируйте следующую строку с надписью line cgi.fix_pathinfo=1.

; cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI.  PHP's
; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok
; what PATH_INFO is.  For more information on PATH_INFO, see the cgi specs.  Setting
; this to 1 will cause PHP CGI to fix its paths to conform to the spec.  A setting
; of zero causes PHP to behave as before.  Default is 1.  You should fix your scripts
; to use SCRIPT_FILENAME rather than PATH_TRANSLATED.
; http://php.net/cgi.fix-pathinfo
cgi.fix_pathinfo=1

Затем откройте второй файл с именем /etc/lighttpd/modules.conf.

vi /etc/lighttpd/modules.conf

Раскомментируйте следующую строку с надписью include «conf.d/fastcgi.conf».

##
## FastCGI (mod_fastcgi)
##
include "conf.d/fastcgi.conf"

Затем откройте третий файл с именем /etc/lighttpd/conf.d/fastcgi.conf.

vi /etc/lighttpd/conf.d/fastcgi.conf

Теперь добавьте следующий контейнер внизу файла и сохраните его.

fastcgi.server += ( ".php" =>
        ((
                "host" => "127.0.0.1",
                "port" => "9000",
                "broken-scriptfilename" => "enable"
        ))
)

Перезапустите службу Lighthttpd, чтобы отразить изменения и включить поддержку PHP.

systemctl restart lighttpd

Шаг 5. Тестирование PHP и PHP-FPM с поддержкой FastCGI в Lighttpd

17. Как мы уже говорили выше, корневым документом по умолчанию для Lighthttpd является /var/www/lighttpd/. Итак, здесь мы создадим файл phpinfo.php в этом каталоге.

vi /var/www/lighttpd/info.php

Добавьте в него следующие строки. Этот небольшой фрагмент кода отобразит информацию об установке PHP и их версиях.

<?php
phpinfo();
?>

18. Откройте браузер и перейдите по следующим ссылкам.

http://Your-Domain.com/info.php
OR
http://Your-IP-addr/info.php

Вы увидите рабочую информацию о PHP, PHP-FPM и MySQL, а также о множестве других уже включенных модулей.