Заменить apache на nginx ubuntu

Обновлено: 02.07.2024

WordPress – это популярная система управления контентом, предназначенная для администрирования сайта или ведения блогов. Платформа WordPress очень гибкая и проста в установке и настройке.

WordPress может взаимодействовать с большинством современных веб-серверов. Самый популярный (возможно, стандартный) вариант – это веб-сервер Apache. Apache отличается надёжностью и постоянной поддержкой сообщества, но иногда (особенно при обслуживании большого количества запросов) он сталкивается с проблемами, связанными с использованием ресурсов.

Nginx – веб-сервер, получивший свою популярность благодаря простоте, гибкости и низкому потреблению ресурсов. Потому многие пользователи постепенно переходят с Apache на Nginx для размещения установки WordPress. В сети можно найти множество руководств по установке WordPress на Nginx, но они не подходят в случае, если нужно переместить уже существующую установку.

Данное руководство поможет выполнить миграцию установки WordPress с веб-сервера Apache на Nginx на сервере Ubuntu 12.04.

Примечание: Предполагается, что система WordPress установлена на Apache согласно этому руководству. В противном случае не забудьте откорректировать некоторые команды согласно вашим данным.

Установка Nginx и PHP5-FPM

Для начала нужно установить сервер Nginx. Его пакеты доступны в стандартных репозиториях Ubuntu.

sudo apt-get update
sudo apt-get install nginx

В отличие от Apache, Nginx по умолчанию не включает основные функции обработки PHP; вместо этого он передаёт эти запросы на выделенный обработчик PHP.

Утилита php5-fpm – стандартный пакет для обработки PHP на сервере Nginx. Чтобы WordPress мог обрабатывать файлы PHP, нужно установить этот пакет.

sudo apt-get install php5-fpm

Теперь все необходимые компоненты установлены.

Настройка PHP5-FPM

На данном этапе нужно подготовить обработчик PHP.

Отредактируйте конфигурационный файл php5-fpm:

sudo nano /etc/php5/fpm/php.ini

Найдите параметр cgi.fix_pathinfo и отредактируйте его следующим образом:

Это мера предосторожности. Если оставить стандартное значение того параметра, 1, то в случае, если запрашиваемый файл не найден, php5-fpm будет пытаться обработать и вернуть файл с наиболее похожим именем. Это серьёзная угроза для безопасности, поскольку так злоумышленник сможет извлечь с сайта конфиденциальную информацию. Лучше настроить php5-fpm для обработки только тех файлов, которые точно соответствуют запросу, а в противном случае возвращать ошибку. Для этого и нужно задать значение 0.

Сохраните и закройте файл.

Теперь нужно отредактировать другой конфигурационный файл PHP, чтобы настроить взаимодействие с веб-сервером.

Найдите директиву listen =. Нужно настроить её для взаимодействия с веб-сервером при помощи сокетов.

Затем сохраните и закройте файл.

Чтобы изменения вступили в силу, перезапустите сервис php5-fpm.

sudo service php5-fpm restart

Создание виртуального хоста Nginx

Теперь нужно подготовить блок server веб-сервера Nginx.

Примечание: Блоки server – полная аналогия виртуальным хостам Apache. Они содержат индивидуальные настройки сайтов. Как правило, блоки server называются виртуальными хостами (понятие из терминологии Apache).

Как и Apache, Nginx в системе Ubuntu настраивает сайты в каталоге sites-available directory, а затем включает их при помощи символьной ссылки в каталог sites-enabled. Чтобы обслуживать установку WordPress при помощи Nginx, нужно отредактировать конфигурационный файл виртуального хоста по умолчанию

sudo nano /etc/nginx/sites-available/default

Удалите всё содержимое файла, чтобы потом заполнить его новыми параметрами.

Сначала нужно создать блок server; это базовый компонент индивидуальных настроек отдельного сайта. Согласно настройкам, Nginx обрабатывает эти файлы при запуске или перезагрузке сервера.

Для начала важно запомнить, что каждый параметр Nginx должен заканчиваться символом точки с запятой (;). В противном случае Nginx не сможет прочесть файл, что, вероятно, вызовет сбой сервера.

Также нужно указать каталог document root, в котором будут храниться файлы WordPress.

Примечание: Согласно другим инструкциям, файлы сайта могут храниться в каталогах /var/www/wordpress, /home/wordpress/public_html и т.п. В таком случае вам нужно отредактировать директиву root , указав правильный каталог.

server listen 80;
root /var/www;
>

Затеем нужно добавить директиву, которая определяет, какие файлы Nginx будет обслуживать в первую очередь. Файл, который используется для описания каталога, называется индексом каталога. В WordPress такой файл называется index.php. Другие индексные файлы, записанные в формате HTML, можно использовать в качестве запасного варианта.

Также нужно указать доменное имя сервера. Это может быть не так важно, если сервер обслуживает единственный сайт на WordPress; однако эта директива позволит в дальнейшем добавить другие сайты без необходимости повторно редактировать этот файл.

Кроме того, в директиве server_name после основного домена можно добавить альтернативные доменные имена сайта (например, домен с префиксом www):

Остальная информация блока server должна быть поделена на блоки location. Блоки location содержат правила, которые определяют действия сервера, если запрос соответствует определенному шаблону.

Создайте блок location для обработки файлов из root-каталога сайта (который был ранее указан в директиве root). Этот блок будет содержать общие правила обслуживания этих файлов.

Добавьте правило, благодаря которому Nginx будет пытаться найти файл, точно соответствующий запросу после доменного имени. Если такого файла не существует, веб-сервер должен попытаться найти каталог с таким же именем. Если такого каталога также не существует, веб-сервер передаст запрос в PHP-скрипт, который попытается найти другой способ обработки запроса.

После этого нужно добавить правило для обработки пересылки данных PHP на php5-fpm. Для подключения оно использует данные конфигурационных файлов php5-fpm.

\.php$ try_files $uri =404;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
>
>

После этого нужно добавить несколько правил Nginx для обслуживания запросов favicon и robot.txt (они используются поисковыми системами для индексирования сайтов). Эти запросы не нужно регистрировать в логах.

Затем добавьте блок location, который отвечает за доступ к скрытым папкам (в системах Linux их имен начинаются с точки). Это заблокирует обслуживание таких файлов, поскольку они могут содержать конфигурации Apache.

В завершение нужно заблокировать обслуживание файлов PHP из каталогов uploads и files. Это защитит сервер от выполнения вредоносного кода.

В целом блок server имеет такой вид:

\.php$ try_files $uri =404;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
>
location = /favicon.ico log_not_found off;
access_log off;
>
location = /robots.txt allow all;
log_not_found off;
access_log off;
>
location

Сохраните и закройте файл. Символьная ссылка между этим файлом и каталогом sites-enabled должна уже существовать, потому при запуске Nginx он будет включен.

Переход с Apache на Nginx

На данный момент Apache обслуживает запросы на порте 80. Это значит, что Nginx не сможет подключиться к этому порту. Нужно остановить веб-сервер Apache, прежде чем включить Nginx.

В некоторых случаях есть необходимость оставить сервер Apache включенным, если он обслуживает другой контент (к примеру, если у вас несколько сайтов, и вы перемещаете на Nginx только один из них). Для этого нужно убрать все ссылки на порт 80 в конфигурации Apache.

Файлы, которые нужно проверить:

Примечание: Также вы можете настроить Nginx как прокси-сервер Apache. Подробнее о такой настройке можно прочитать здесь.

Изменив порт Apache, перезапустите веб-сервер, чтобы обновить настройки, а затем включите Nginx. После этого порт 80 будет занят сервером Nginx, а Apache будет использовать новый порт.

sudo service apache2 reload && sudo service nginx start

Если же в дальнейшем сервер Apache не нужен, так как обслуживание файлов полностью перейдёт к Nginx, выключите Apache:

sudo service apache2 stop && sudo service nginx start

На данном этапе важно либо передать порт 80 серверу Nginx, настроив Apache на другой порт, либо же полностью остановить Apache. В противном случае Nginx не запустится, потому что порт занят другим веб-сервером.

Если переход был выполнен успешно и теперь контент обслуживается сервером Nginx, можно удалить Apache и его зависимости, если он больше не нужен. Для этого введите:

dpkg --get-selections | grep apache
apache2 install
apache2-mpm-prefork install
apache2-utils install
apache2.2-bin install
apache2.2-common install
libapache2-mod-auth-mysql install
libapache2-mod-php5 install

А затем удалите эти пакеты:

sudo apt-get remove apache2 apache2-mpm-prefork apache2-utils apache2.2-bin apache2.2-common libapache2-mod-auth-mysql libapache2-mod-php5

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

sudo apt-get autoremove

Заключение

Теперь установка WordPress обслуживается сервером Nginx. В целом, серверы Apache и Nginx работают почти одинаково, однако Nginx требует меньше ресурсов, а это очень важно, если сайт получает большое количество трафика. Чем меньше ресурсов нужно серверу, тем лучше он справляется с большими объёмами трафика.

There are a number of choices you have to make when getting a website or application up and running. Sometimes, your requirements change, new technology becomes viable, or your user-base balloons unexpectedly. Regardless of your reasons, one of the components of your application stack that you might consider changing is the web server.

Although the Apache web server is currently the most popular web server in the world, Nginx is gaining ground at a rapid rate. This is unsurprising, considering that Nginx performs excellent while using few resources. For many websites, a migration to Nginx would improve performance.

In this guide, we will discuss how to migrate a website from Apache to Nginx on an Ubuntu 12.04 VPS. We will attempt to remain general in our suggestions, but will give you hints on some areas that you might need to tweak for your own purposes.

This guide assumes that you have installed a LAMP (Linux, Apache, MySQL, and PHP) stack using this tutorial. If you simply selected the one-click LAMP image when creating your droplet, your server will have this configuration as well.

Install Nginx

The first thing that we will do to begin migrating our websites is to install our new server software. This will allow us to configure our new server by looking at our current Apache configuration files for guidance.

Luckily, Nginx is present in the Ubuntu repositories by default. Let’s install it now:

One implementation detail that becomes very important in our use-case is that Nginx offloads any dynamic handling to a separate process. This allows Nginx to remain lean and fast. It can focus on its core functionality without having to try to add PHP support through modules. Instead, it just offloads that to an application that is built for that purpose.

This is all being mentioned at this point to say that we also need to install a PHP handler in order to process PHP scripts. The standard choice is php5-fpm , which performs well with Nginx:

You should have all of the software you need to change your site over to Nginx. We still need to configure our software to emulate the configuration that Apache was running under.

Set Up Test Nginx Configuration

Since we have Apache running currently, if we can avoid it, we would like to configure our Nginx server independently of Apache so that our site will still be operational during the transition.

This is as simple as testing Nginx on an alternative port until we are ready to solidify our changes. This way, we can run the two servers concurrently.

Begin by opening the configuration file for the default Nginx site:

Save and close the file. This is a good time to do a spot check to see that we can access our Nginx server. Start Nginx to test this:

Use the port number we configured to access the default Nginx configuration. Type this into your browser:

DigitalOcean Nginx default page

Your Apache instance should still be running on the default port 80. You can check this as well by visiting your site without the :8000 at the end (our example is just serving the default Apache page. If you had configured your website, that would be here instead):

DigitalOcean Apache default page

Translate Your Apache Configuration

Now that you have both servers up and running, you can begin migrating and translating your Apache configuration for use with Nginx. This must be done manually, so it is important that you understand how Nginx is configured.

This task will mainly come down to writing Nginx server blocks, which are analogous to Apache virtual servers. Apache keeps these files in /etc/apache2/sites-available/ and Nginx follow suit and keeps its server block declarations in /etc/nginx/sites-available/ on Ubuntu.

For each virtual server declaration, you’ll be creating a server block. If you go through your Apache files, you will probably find virtual hosts that look like this:

We can begin to build our Nginx server block using this configuration.

In your /etc/nginx/sites-available/ directory, open the file we edited before to declare the Nginx port:

Disregarding the commented lines for the moment, it should look something like this:

You should already begin to see some of the items that seem to correspond to our Apache configuration. Generally speaking, the main directives translate like this:

If we were going to create a server block that emulates the functionality of the virtual host file from above, it might look something like this:

We have eliminated some items and also added a few extra lines that we should explain.

Firstly, the error log lines have been eliminated from the configuration. This is because they are already defined in the /etc/nginx/nginx.conf file. This provides us with a default that we will use.

We have also eliminated the ServerAdmin directive because Nginx does not embed that information in its error pages.

The PHP handling has changed a bit as well. Due to the fact that PHP is handled separately in Nginx, we pass these files off to the php-fpm program we installed earlier. This is implemented through a socket (which we will need to configure momentarily).

The documentation section is changed to reflect the Nginx documentation. It otherwise functions fairly similarly.

Lastly, we configure Nginx to deny access to any .htaccess or other files that begin with .ht in our directory. These are Apache-specific configuration files, and they do not work with Nginx. It is safer to not expose these configuration files.

Save and close the file when you are finished.

We must restart our Nginx server for these changes to be recognized:

Configure PHP-FPM

Now that we have most of the Nginx configuration out of the way, we need to modify the php-fpm configuration to communicate using the channels we specified.

To begin with, we should modify the php.ini file so that it doesn’t serve files insecurely.

The line that we need to modify will require PHP to serve the exact file requested instead of guessing if there is an incomplete match. This prevents PHP from possibly serving or exposing sensitive data to someone who is probing the PHP handler for weaknesses.

Find the line that specifies the cgi.fix_pathinfo directive and modify it so that it looks like:

Save and exit out of this file.

Next, we will change the way that php-fpm connects to our server. Open this file in your editor:

Find and modify the listen directive to match the value that we put in the server block configuration file:

If you end up running into problems with handling a lot of PHP requests, you might want to come back here and increase the number of child processes that can be spawned at once. The line you want to change is:

Save and close this file.

Now, our php-fpm program should be configured correctly. We need to restart it for our changes to propagate.

It won’t hurt to restart Nginx again as well:

Test that any PHP files that you have in your root directory function correctly. You should be able to get PHP files to execute just as they were in Apache.

If we access the info.php file that we created in the Ubuntu LAMP tutorial, it should render like this:

DigitalOcean Nginx PHP files

In the PHP Variables section, you should see Nginx listed as the “SERVER_SOFTWARE” variable:

DigitalOcean Nginx server software

Transition Your Nginx Site Live

After you have done extensive testing, you can try to seamlessly transition your site from Apache to Nginx.

This is possible due to the fact that neither of these servers implement changes until they are restarted. This allows us to set everything up, and then flip the switch in one instant.

Really, the only thing we need to do is modify the port in the Nginx server block. Open the file now:

Save and close the file.

If you are only transitioning some of your sites to Nginx and continuing to serve some content from Apache, you need to disable the Apache virtual servers that serve requests on port 80. This is necessary to avoid conflicts. If this is not done correctly, Nginx will fail to start because the port will already be taken.

If you’re planning on continuing to run Apache, check these files and locations for port 80 usage:

After you are satisfied that you have changed all of the necessary ports, you can restart both services like this:

Apache should reload, releasing port 80. Immediately afterward, Nginx should reload and start accepting connections on that port. If all went smoothly, your site should now be served by Nginx.

If you are not going to be using Apache anymore to serve any portion of your sites, you can completely stop its web process instead:

If you are not using Apache anymore, you can uninstall the Apache files at this point. You can easily find the Apache-related files by typing:

You can then uninstall them with apt-get. For example:

You can also remove all of the dependency packages that are no longer needed:

Migration Complications

There are a few things that are common in the Apache world that may cause you some confusion when trying to switch to Nginx.

Rewrite Translations and .htaccess Files

One of the most fundamental differences is that Nginx does not respect directory overrides.

Apache uses .htaccess files, together with an AllowOverride All directive in a location block. This allows you to put directory-specific configurations in the directory that houses the files.

Nginx does not allow these files. Housing the configuration with the files being served is potentially a security problem if misconfigured, and it is easy to look at the centralized configuration files and not realize that a setting is being overwritten through an .htaccess file.

As a result, all configuration that you have listed in an active .htaccess file must be placed within the location block in the server block configuration for that host. This is not generally any more complicated, but you must translate these rules just as you did with the virtual host definitions.

A common thing to keep in .htaccess files are rules for Apache’s mod_rewrite module, which alters the access URLs of content to be more user-friendly. Nginx has a rewrite module that is similar, but uses different syntax. Unfortunately, rewriting URLs in Nginx is outside of the scope of this guide.

Module and Outside Configuration Complications

Another thing to keep in mind is that you need to be conscious of what functionality the Apache modules that you have enabled are providing.

A simple example is the dir module. When enabled, you can specify the order of the files that Apache will attempt to serve as a directory index by placing a line like this in your virtual host file:

This line will determine the handling that will happen for this virtual host. However, if this line is not present, and the dir module is enabled, the order of files being served will be determined by this file:

The point of bringing this up is that you have to be aware of the possibility that a module, or an externally sourced configuration of any kind, for that matter, might be doing something behind-the-scenes that you will have to do explicitly in Nginx.

In this example, you can specify the directory index order in Nginx by adding this to a server block:

It is important to keep this in mind.

One thing that might be helpful if you are transitioning a complex site configuration is to copy and paste all of the separately sourced configuration files into one monolithic file and systematically go through and translate each line.

This might be a headache, but for a production server, it could save you a lot of time tracking down what is causing strange behavior that you cannot quite pin down.

Conclusion

The complexity of transitioning from Apache to Nginx is almost completely dependent on the complexity of your specific configurations. Nginx can handle pretty much anything that Apache can, with the benefit of doing so with less resources. This means that your site can smoothly serve a larger pool of users.

While migrating does not make sense for all sites, and while Apache is a wonderful server that adequately serves the needs of many projects, you may see performance gains or increases in scalability with Nginx. If you still require Apache, another alternative is using Nginx as a reverse-proxy for your Apache server. This approach can leverage the strengths of both servers in a powerful way.

Apache и Nginx — два популярных веб-сервера с открытым исходным кодом, часто используемые с PHP. Одновременный запуск обоих серверов на одной виртуальной машине может быть полезным в ситуации с хостингом нескольких сайтов с разными требованиями. Обычно для запуска двух веб-серверов на одной системе используются разные IP-адреса или разные номера портов.

В этом руководстве вы настроите Nginx как веб-сервер и обратный прокси-сервер для Apache — все на одном сервере.

В зависимости от веб-приложения для обеспечения осведомленности Apache о присутствии обратного прокси-сервера могут потребоваться изменения кода, особенно если настроены сайты SSL. Чтобы избежать этого, нужно установить модуль Apache под названием mod_rpaf , который перезаписывает определенные переменные среды так, что все выглядит, как если бы Apache напрямую обрабатывал запросы веб-клиентов.

Предварительные требования

Для прохождения данного обучающего руководства вам потребуется следующее:

  • Новый сервер Ubuntu 18.04, настроенный в соответствии с указаниями документа «Начальная настройка сервера с Ubuntu 18.04», с пользователем sudo non-root и брандмауэром.
  • Четыре полностью квалифицированных доменных имени, настроенных на указание на IP-адрес вашего сервера. В разделе «Шаг 3. Настройка имени хоста с DigitalOcean» показано, как можно это сделать. Если вы размещаете DNS ваших доменов в других местах, нужно создать соответствующие записи уровня A именно там.

Шаг 1 — Установка Apache и PHP-FPM

Начнем с установки Apache и PHP-FPM.

Помимо Apache и PHP-FPM мы также установим модуль PHP FastCGI Apache, libapache2-mod-fastcgi , для поддержки веб-приложений FastCGI.

Вначале обновите свой список пакетов и убедитесь, что у вас установлены последние версии пакетов.

Затем выполните установку пакетов Apache и PHP-FPM:

Далее изменим конфигурацию Apache по умолчанию для использования PHP-FPM.

Шаг 2 — Настройка Apache и PHP-FPM

На этом шаге мы изменим номер порта Apache на 8080 и настроим его для работы с PHP-FPM с использованием модуля mod_fastcgi . Переименуйте файл конфигурации Apache ports.conf :

Создайте новый файл ports.conf и установите в нем порт 8080 :

Примечание. Веб-серверы обычно настраиваются на прослушивание адреса 127.0.0.1:8080 при настройке в качестве обратного прокси-сервера, однако при этом для переменной среды PHP SERVER_ADDR будет установлено значение циклического IP-адреса, а не публичного IP-адреса сервера. Наша цель — настроить сервер Apache так, чтобы сайты не видели обратный прокси-сервер перед ним. Поэтому мы настроим его для прослушивания порта 8080 на всех IP-адресах.

Далее мы создадим файл виртуального хоста для Apache. Директива <VirtualHost> этого файла будет установлена для обслуживания только сайтов на порту 8080 .

Отключите виртуальный хост по умолчанию:

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

Откройте новый файл конфигурации:

Измените порт прослушивания на 8080:

Сохраните файл и активируйте новый файл конфигурации:

Затем перезагрузите Apache:

Убедитесь, что Apache прослушивает порт 8080 :

Результат должен выглядеть как в следующем примере, где apache2 прослушивает порт 8080 :

Убедившись, что Apache прослушивает правильный порт, вы можете настроить поддержку PHP и FastCGI.

Шаг 3 — Настройка Apache для использования mod_fastcgi

По умолчанию Apache обслуживает страницы PHP с помощью модуля mod_php , однако для работы с PHP-FPM ему требуется дополнительная настройка.

Примечание. Если вы пытаетесь использовать это обучающее руководство в существующей системе LAMP с mod_php, вначале выполните отключение с помощью команды sudo a2dismod php7.2 .

Мы добавим блок конфигурации для mod_fastcgi, зависящий от mod_action . По умолчанию mod_action отключен, и предварительно его нужно включить:

Переименуйте существующий файл конфигурации FastCGI:

Создайте новый файл конфигурации:

Добавьте в файл следующие директивы для передачи запросов файлов .php в сокет PHP-FPM UNIX:

Сохраните изменения и проведите тест конфигурации:

Если отображается Syntax OK, перезагрузите Apache:

Если отображается предупреждение Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message. , его можно игнорировать. Мы настроим имена серверов позднее.

Теперь убедимся, что мы можем обслуживать PHP из Apache.

Шаг 4 — Проверка функционала PHP

Чтобы убедиться, что PHP работает, мы создадим файл phpinfo() и получим к нему доступ к через браузер.

Создайте файл /var/www/html/info.php , содержащий вызов функции phpinfo :

phpinfo Server API

phpinfo PHP Variables

Убедитесь, что в Server API вверху страницы указано значение FPM/FastCGI. Раздел «Переменные PHP» в нижней трети страницы покажет, что параметр SERVER_SOFTWARE имеет значение Apache на Ubuntu. Это подтверждает, что модуль mod_fastcgi активен, и что Apache использует PHP-FPM для обработки файлов PHP.

Шаг 5 — Создание виртуальных хостов для Apache

Вначале создайте корневые каталоги документа:

Затем создайте файл index для каждого сайта:

Далее создайте файл phpinfo() для каждого сайта, чтобы мы могли протестировать правильность конфигурации PHP.

Добавьте в файл следующий код для определения хоста:

Строка AllowOverride All активирует поддержку .htaccess.

Это только базовые указания. Полное руководство по по настройке виртуальных хостов в Apache можно найти в документе «Настройка виртуальных хостов Apache в Ubuntu 16.04».

Сохраните и закройте файл. Затем создайте аналогичную конфигурацию для test.io . Сначала создайте файл:

Затем добавьте в файл конфигурацию:

Сохраните файл и выйдите из редактора.

Теперь, когда вы создали оба виртуальных хоста Apache, разрешите сайтам использовать команду a2ensite . Это создаст символическую связь с файлом виртуального хоста в каталоге sites-enabled :

Снова проверьте Apache на наличие ошибок конфигурации:

Когда в конфигурации не останется ошибок, перезагрузите Apache, чтобы применить изменения:

Вы увидите следующие результаты:

страница индекса foobar.net

страница индекса test.io

Для каждого сайта вы увидите такой же перечень настроек PHP, что и на шаге 4.

Мы разместили два сайта на сервере Apache на порту 8080 . Теперь давайте настроим Nginx.

Шаг 6 — Установка и настройка Nginx

Установите Nginx с помощью диспетчера пакетов:

Затем удалите соединение symlink по умолчанию виртуального хоста, поскольку мы больше не будем его использовать:

Теперь мы создадим виртуальные хосты для Nginx, используя ту же процедуру, что использовалась для Apache. Вначале необходимо создать корневые каталоги документов для обоих сайтов:

Мы будем хранить сайты Nginx в каталоге /usr/share/nginx , где Nginx требуется хранить их по умолчанию. Вы можете поместить их в каталог /var/www/html с сайтами Apache, но разделение поможет привязать сайты к Nginx.

Как и в случае с виртуальными хостами Apache, после завершения настройки следует создать файлы index и phpinfo() для тестирования:

Добавьте в файл следующее:

Сохраните и закройте файл.

Затем активируйте оба сайта, создав символические ссылки на каталог sites-enabled :

Протестируйте конфигурацию Nginx и убедитесь в отсутствии проблем с конфигурацией:

При обнаружении ошибок перезагрузите Nginx:

Переменные Nginx PHP Variables

[SERVER_SOFTWARE] должен иметь значение nginx , указывая, что файлы обслуживались Nginx напрямую. [DOCUMENT_ROOT] должен указывать на каталог, ранее созданный на этом шаге для каждого из сайтов Nginx.

К настоящему моменту мы установили Nginx и создали два виртуальных хоста. Далее мы настроим Nginx на запросы прокси-сервера, предназначенные для доменов Apache.

Шаг 7 — Настройка Nginx для виртуальных хостов Apache

Создадим дополнительный виртуальный хост Nginx с несколькими именами доменов в директивах server_name . Запросы этих доменных имен будут перенаправляться через прокси-сервер в Apache.

Создайте новый файл виртуального хоста Nginx для перенаправления запросов в Apache:

Добавьте следующий блок кода, указывающий имена доменов виртуального хоста Apache и перенаправляющий их запросы в Apache. Обязательно используйте публичный IP-адрес в proxy_pass :

Сохраните файл и активируйте новый файл виртуального хоста, создав символическую ссылку:

Протестируйте конфигурацию и убедитесь в отсутствии ошибок:

Если ошибок нет, перезагрузите Nginx:

phpinfo для Apache через Nginx

Мы успешно настроили Nginx для перенаправления запросов определенных доменов в Apache через прокси-сервер. Теперь настроим Apache для установки переменной REMOTE_ADDR , как если бы эти запросы обрабатывались напрямую.

Шаг 8 — Установка и настройка mod_rpaf

Установите пакеты, необходимые для построения модуля:

Загрузите последний стабильный выпуск из GitHub:

Выполните извлечение загруженного файла:

Перейдите в новый каталог, содержащий файлы:

Скомпилируйте и установите модуль:

Затем создайте в каталоге mods-available файл, который будет загружать модуль rpaf ,

Добавьте в файл следующий код для загрузки модуля:

Сохраните файл и выйдите из редактора.

Создайте в этом каталоге другой файл с именем rpaf.conf , который будет содержать директивы конфигурации для mod_rpaf :

Добавьте следующий блок кода для настройки mod_rpaf и обязательно укажите IP-адрес своего сервера:

Здесь приведено краткое описание каждой директивы. Дополнительную информацию можно найти в файле README по модулю mod_rpaf .

Сохраните rpaf.conf и активируйте модуль:

При этом создаются символические ссылки файлов rpaf.load и rpaf.conf в каталоге mods-enabled . Теперь протестируем конфигурацию:

Если ошибок нет, перезагрузите Apache:

Теперь настроим шифрование TLS/SSL для каждого сайта.

На этом шаге мы настроим сертификаты TLS/SSL для обоих доменов, размещенных в Apache. Мы получим сертификаты посредством Let’s Encrypt. Nginx поддерживает конечные узлы SSL, и поэтому мы можем настроить SSL без изменения файлов конфигурации Apache. Модуль mod_rpaf обеспечивает установку в Apache переменных среды, необходимых для бесшовной работы приложений за обратным прокси-сервером SSL.

Вначале мы разделим блоки server <. >обоих доменов так, что у каждого из них будет собственный сертификат SSL. Откройте в своем редакторе файл /etc/nginx/sites-available/apache :

Мы используем Certbot для генерирования сертификатов TLS/SSL. Плагин Nginx изменит конфигурацию Nginx и перезагрузит ее, когда это потребуется.

Прежде всего, добавьте официальное хранилище Certbot:

Нажмите ENTER в диалоге, чтобы подтвердить добавление нового хранилища. Обновите список пакетов, чтобы получить данные пакета нового хранилища:

Установите пакет Certbot’s Nginx с apt :

Эта команда указывает Certbot, что нужно использовать плагин nginx , а параметр -d задает имена, для которых должен действовать сертификат.

Если это первый запуск certbot , вам будет предложено указать адрес эл. почты и принять условия обслуживания. После этого certbot свяжется с сервером Let’s Encrypt и отправит запрос с целью подтвердить, что вы контролируете домен, для которого запрашиваете сертификат.

Выберите желаемый вариант и нажмите ENTER . Конфигурация будет обновлена, а затем будет выполнена перезагрузка Nginx для активации новых настроек.

Теперь выполните команду для второго домена:

phpinfo ssl

Теперь отключим прямой доступ к Apache.

Шаг 10 — Блокировка прямого доступа к Apache (опционально)

Поскольку Apache прослушивает порт 8080 на публичном IP-адресе, он доступен кому угодно. Его можно заблокировать с помощью следующей команды IPtables в наборе правил брандмауэра.

Примечание. По умолчанию правила IPtables теряют силу после перезагрузки системы. Существует несколько способов сохранения правил IPtables, но проще всего использовать параметр iptables-persistent в хранилище Ubuntu. Прочитайте эту статью, чтобы узнать больше о настройке IPTables.

Теперь настроим Nginx для обслуживания статических файлов для сайтов Apache.

Шаг 11 — Обслуживание статических файлов с помощью Nginx (необязательно)

Когда Nginx перенаправляет запросы доменов Apache через прокси-сервер, каждый запрос файла этого домена отправляется в Apache. Nginx обслуживает статические файлы, такие как изображения, JavaScript и таблицы стилей, быстрее Apache. Поэтому мы настроим файл виртуального хоста Nginx apache для прямого обслуживания статических файлов и перенаправления запросов PHP в Apache.

Откройте в своем редакторе файл /etc/nginx/sites-available/apache :

Вам потребуется добавить два дополнительных блока location в каждый блок server, а также изменить существующие разделы location . Кроме того, вам нужно будет указать Nginx, где можно найти статические файлы для каждого сайта.

Если вы решили не использовать сертификаты SSL и TLS, измените свой файл, чтобы он выглядел следующим образом:

Директива try_files указывает Nginx искать файлы в корне документа document root и выводить их напрямую. Если файл имеет расширение .php , запрос перенаправляется в Apache. Даже если файл отсутствует в document root, запрос перенаправляется в Apache, чтобы функции приложения (например, постоянные ссылки) работали без проблем.

Предупреждение. Директива location

/\.ht очень важна, поскольку она не дает Nginx выводить содержимое файлов конфигурации Apache с важными данными, таких как .htaccess и .htpasswd .

Сохраните файл и проведите тест конфигурации:

Если тест завершается успешно, перезагрузите Nginx:

Затем откройте страницы index.html каждого сайта, и вы не увидите записи журнала Apache. Их обслуживает Nginx.

Завершив изучение файла журнала, нажмите CTRL+C, чтобы остановить отслеживание.

При такой настройке Apache не сможет ограничивать доступ к статическим файлам. Контроль доступа к статическим файлам должен быть настроен в файле apache виртуального хоста Nginx, однако это не входит в содержание настоящего обучающего руководства.

Apache and Nginx are two popular open-source web servers often used with PHP. It can be useful to run both of them on the same virtual machine when hosting multiple websites that have varied requirements. The general solution for running two web servers on a single system is to either use multiple IP addresses or different port numbers.

In this tutorial you’ll configure Nginx as both a web server and as a reverse proxy for Apache – all on a single server.

Depending on the web application, code changes might be required to keep Apache reverse-proxy-aware, especially when SSL sites are configured. To avoid this, you will install an Apache module called mod_rpaf which rewrites certain environment variables so it appears that Apache is directly handling requests from web clients.

We will host four domain names on one server. Two will be served by Nginx: nginx1. your_domain (the default virtual host) and nginx2. your_domain . The remaining two, apache1. your_domain and apache2. your_domain , will be served by Apache. We’ll also configure Apache to serve PHP applications using PHP-FPM, which offers better performance over mod_php .

Prerequisites

To complete this tutorial, you’ll need the following:

    configured by following the Initial Server Setup with Ubuntu 20.04, with a sudo non-root user and a firewall.
  • Four fully-qualified domain names configured to point to your server’s IP address. See Step 3 of How To Set Up a Host Name with DigitalOcean for an example of how to do this. If you host your domains’ DNS elsewhere, you should create appropriate A records there instead.

Step 1 — Installing Apache and PHP-FPM

Let’s start by installing Apache and PHP-FPM.

In addition to Apache and PHP-FPM, we will also install the PHP FastCGI Apache module, libapache2-mod-fastcgi , to support FastCGI web applications.

First, update your package list to ensure you have the latest packages.

Next, install the Apache and PHP-FPM packages:

Next, let’s change Apache’s default configuration to use PHP-FPM.

Step 2 — Configuring Apache and PHP-FPM

In this step we will change Apache’s port number to 8080 and configure it to work with PHP-FPM using the mod_fastcgi module. Rename Apache’s ports.conf configuration file:

Create a new ports.conf file with the port set to 8080 :

Note: Web servers are generally set to listen on 127.0.0.1:8080 when configuring a reverse proxy but doing so would set the value of PHP’s environment variable SERVER_ADDR to the loopback IP address instead of the server’s public IP. Our aim is to set up Apache in such a way that its websites do not see a reverse proxy in front of it. So, we will configure it to listen on 8080 on all IP addresses.

Next we’ll create a virtual host file for Apache. The <VirtualHost> directive in this file will be set to serve sites only on port 8080 .

Disable the default virtual host:

Then create a new virtual host file, using the existing default site:

Now open the new configuration file:

Change the listening port to 8080 :

Save the file and activate the new configuration file:

Then reload Apache:

Install the net-tools package which contains the netstat command:

Verify that Apache is now listening on 8080 :

The output should look like the following example, with apache2 listening on 8080 :

Once you verify that Apache is listening on the correct port, you can configure support for PHP and FastCGI.

Step 3 — Configuring Apache to Use mod_fastcgi

Apache serves PHP pages using mod_php by default, but it requires additional configuration to work with PHP-FPM.

Note: If you are trying this tutorial on an existing installation of LAMP with mod_php , disable it first with sudo a2dismod php7.4 .

We will be adding a configuration block for mod_fastcgi , which depends on mod_action . mod_action is disabled by default, so we first need to enable it:

Rename the existing FastCGI configuration file:

Create a new configuration file:

Add the following directives to the file to pass requests for .php files to the PHP-FPM UNIX socket:

Save the changes and perform a configuration test:

Note: If you see the warning Could not reliably determine the server's fully /
qualified domain name, using 127.0.1.1. Set the /'ServerName' directive globally/
to suppress this message. , you can safely ignore it for now. We’ll configure server names later.

Reload Apache as long as Syntax OK is displayed:

Now let’s make sure we can serve PHP from Apache.

Step 4 — Verifying PHP Functionality

Let’s make sure that PHP works by creating a phpinfo() file and accessing it from a web browser.

Create the file /var/www/html/info.php , which contains a call to the phpinfo function:

Note that if you followed the initial server setup in the Prerequisites section, then you likely enabled the Apache firewall. Let’s go ahead and make sure that we can access our IP on port 8080 , which is not currently accessible. We’ll restrict public access to this port in Step 10.

First allow port 8080 through the firewall:

Since we are going to secure our Apache domains, let’s go ahead and make sure TLS traffic on port 443 can enter.

Allow Apache Full to permit traffic on ports 80 and 443 :

Now check your firewall status:

If you followed the prerequisites, then the output will look like this:

You will see that port 8080 and Apache Full are allowed alongside any other firewall rules. Now let’s view our info.php page.

phpinfo Server API

phpinfo PHP Variables

At the top of the page, check that Server API says FPM/FastCGI. About two-thirds of the way down the page, the PHP Variables section will tell you the SERVER_SOFTWARE is Apache on Ubuntu. These confirm that mod_fastcgi is active and Apache is using PHP-FPM to process PHP files.

Step 5 — Creating Virtual Hosts for Apache

Let’s create Apache virtual host files for the domains apache1. your_domain and apache2. your_domain . To do that, we’ll first create document root directories for both sites and place some default files in those directories so we can easily test our configuration.

First, create the document root directories:

Then create an index file for each site:

Then create a phpinfo() file for each site so we can test that PHP is configured properly.

Now create the virtual host file for apache1. your_domain :

Add the following code to the file to define the host:

The line AllowOverride All enables .htaccess support.

These are only the most basic directives. For a complete guide on setting up virtual hosts in Apache, see How To Set Up Apache Virtual Hosts on Ubuntu 18.04.

Save and close the file. Then create a similar configuration for apache2. your_domain . First create the file:

Then add the configuration to the file:

Save the file and exit the editor.

Now that both Apache virtual hosts are set up, enable the sites using the a2ensite command. This creates a symbolic link to the virtual host file in the sites-enabled directory:

Check Apache for configuration errors again:

You’ll see Syntax OK displayed if there are no errors. If you see anything else, review the configuration and try again.

Reload Apache to apply the changes once your configuration is error-free:

You’ll see the following results:

apache1 index page

apache2 index page

You’ll see the same PHP configuration spec list on each site as you saw in Step 4.

We now have two websites hosted on Apache at port 8080 . Let’s configure Nginx next.

Step 6 — Installing and Configuring Nginx

In this step we’ll install Nginx and configure the domains nginx1. your_domain and nginx2. your_domain as Nginx’s virtual hosts. For a complete guide on setting up virtual hosts in Nginx, see How To Set Up Nginx Server Blocks (Virtual Hosts) on Ubuntu 20.04.

Install Nginx using the apt package manager:

We’ll create our own default site later ( nginx1. your_domain ).

Now we’ll create virtual hosts for Nginx using the same procedure we used for Apache. First create document root directories for both the websites:

We’ll keep the Nginx web sites in /usr/share/nginx , which is where Nginx wants them by default. You could put them under /var/www/html with the Apache sites, but this separation may help you associate sites with Nginx.

As you did with Apache’s virtual hosts, create index and phpinfo() files for testing after setup is complete:

Now create a virtual host file for the domain nginx1. your_domain :

Save and close the file. Now create a virtual host file for Nginx’s second domain, nginx2. your_domain :

Add the following to the file:

Save and close the file.

Enable both sites by creating symbolic links to the sites-enabled directory:

Test the Nginx configuration to ensure there are no configuration issues:

Then reload Nginx if there are no errors:

[“SERVER_SOFTWARE”] should say nginx , indicating that the files were directly served by Nginx. [“DOCUMENT_ROOT”] should point to the directory you created earlier in this step for each Nginx site.

At this point, we have installed Nginx and created two virtual hosts. Next we will configure Nginx to proxy requests meant for domains hosted on Apache.

Step 7 — Configuring Nginx for Apache’s Virtual Hosts

Let’s create an additional Nginx virtual host with multiple domain names in the server_name directives. Requests for these domain names will be proxied to Apache.

Create a new Nginx virtual host file to forward requests to Apache:

Add the following code block; it specifies the names of both Apache virtual host domains and proxies their requests to Apache. Remember to use the public IP address in proxy_pass :

Save the file and enable this new virtual host by creating a symbolic link:

Test the configuration to ensure there are no errors:

If there are no errors, reload Nginx:

We have successfully set up Nginx to proxy requests for specific domains to Apache. Next, let’s configure Apache to set the REMOTE_ADDR variable as if it were handling these requests directly.

Step 8 — Installing and Configuring mod_rpaf

Move to your home directory and install the packages needed to build the module:

Download the latest stable release from GitHub:

Extract the downloaded file:

Change into the new directory containing the files:

Compile and install the module:

Next, create a file in the mods-available directory that will load the rpaf module:

Add the following code to the file to load the module:

Save the file and exit the editor.

Create another file in this directory called rpaf.conf that will contain the configuration directives for mod_rpaf :

Add the following code block to configure mod_rpaf , making sure to specify the IP address of your server:

Here’s a brief description of each directive. See the mod_rpaf README file for more information.

Save rpaf.conf and enable the module:

This creates symbolic links of the files rpaf.load and rpaf.conf in the mods-enabled directory. Now do a configuration test:

Reload Apache if there are no errors:

Now let’s set up TLS/SSL encryption for each site.

First we will separate the server <. >blocks of both the domains so that each of them can have their own SSL certificates. Open the file /etc/nginx/sites-available/apache in your editor:

Modify the file so that it looks like this, with apache1. your_domain and apache2. your_domain in their own server blocks:

We’ll use Certbot to generate our TLS/SSL certificates. Its Nginx plugin will take care of reconfiguring Nginx and reloading the config whenever necessary.

Install certbot using snapd

This command tells Certbot to use the nginx plugin, using -d to specify the names we’d like the certificate to be valid for.

Now execute the command for the second domain:

Now let’s disable direct access to Apache.

Step 10 — Blocking Direct Access to Apache (Optional)

Since Apache is listening on port 8080 on the public IP address, it is accessible by everyone. It can be blocked by working the following IPtables command into your firewall rule set.

The browser should display an “Unable to connect” or “Webpage is not available” error message. With the IPtables tcp-reset option in place, an outsider would see no difference between port 8080 and a port that doesn’t have any service on it.

Note: IPtables rules do not survive a system reboot by default. There are multiple ways to preserve IPtables rules, but the easiest is to use iptables-persistent in Ubuntu’s repository. Explore this article to learn more about how to configure IPTables.

Now let’s configure Nginx to serve static files for the Apache sites.

Step 11 — Serving Static Files Using Nginx (Optional)

When Nginx proxies requests for Apache’s domains, it sends every file request for that domain to Apache. Nginx is faster than Apache at serving static files like images, JavaScript and style sheets. So let’s configure Nginx’s apache virtual host file to directly serve static files but send PHP requests on to Apache.

Open the file /etc/nginx/sites-available/apache in your editor:

You’ll need to add two additional location blocks to each server block, as well as modify the existing location sections. Additionally, you’ll need to tell Nginx where to find the static files for each site.

If you’ve decided not to use SSL and TLS certificates, modify your file so it looks like this:

The try_files directive makes Nginx look for files in the document root and directly serve them. If the file has a .php extension, the request is passed to Apache. Even if the file is not found in the document root, the request is passed on to Apache so that application features like permalinks work without problems.

Warning: The location

/\.ht directive is very important; this prevents Nginx from serving the contents of Apache configuration files like .htaccess and .htpasswd , which contain sensitive information.

Save the file and perform a configuration test:

Reload Nginx if the test succeeds:

To verify things are working, you can examine Apache’s log files in /var/log/apache2 and see the GET requests for the info.php files of apache2. your_domain and apache1. your_domain . Use the tail command to see the last few lines of the file, and use the -f switch to watch the file for changes:

Now visit apache1. your_domain /info.php or apache2. your_domain /info.php in your browser and then look at the output from the log. You’ll see that Apache is indeed replying (your port will be 80 or 443 depending on whether or not you secured the instance):

Then visit the index.html page for each site and you won’t see any log entries from Apache. Nginx is serving them.

When you’re done observing the log file, press CTRL+C to stop tailing it.

With this setup, Apache will not be able to restrict access to static files. Access control for static files would need to be configured in Nginx’s apache virtual host file, but that’s beyond the scope of this tutorial.

Conclusion

You now have one Ubuntu server with Nginx serving nginx1. your_domain and nginx2. your_domain , along with Apache serving apache1. your_domain and apache2. your_domain . Though Nginx is acting as a reverse-proxy for Apache, Nginx’s proxy service is transparent and connections to Apache’s domains appear be served directly from Apache itself. You can use this method to serve secure and static sites.

Читайте также: