Linux nginx config location

Руководство для начинающих

В этом руководстве даётся начальное введение в nginx и описываются некоторые простые задачи, которые могут быть решены с его помощью. Предполагается, что nginx уже установлен на компьютере читателя. Если нет, см. Установка nginx. В этом руководстве описывается, как запустить и остановить nginx и перезагрузить его конфигурацию, объясняется, как устроен конфигурационный файл, и описывается, как настроить nginx для раздачи статического содержимого, как настроить прокси-сервер на nginx, и как связать nginx с приложением FastCGI.

У nginx есть один главный и несколько рабочих процессов. Основная задача главного процесса — чтение и проверка конфигурации и управление рабочими процессами. Рабочие процессы выполняют фактическую обработку запросов. nginx использует модель, основанную на событиях, и зависящие от операционной системы механизмы для эффективного распределения запросов между рабочими процессами. Количество рабочих процессов задаётся в конфигурационном файле и может быть фиксированным для данной конфигурации или автоматически устанавливаться равным числу доступных процессорных ядер (см. worker_processes).

Как работают nginx и его модули, определяется в конфигурационном файле. По умолчанию, конфигурационный файл называется nginx.conf и расположен в каталоге /usr/local/nginx/conf , /etc/nginx или /usr/local/etc/nginx .

Запуск, остановка, перезагрузка конфигурации

Чтобы запустить nginx, нужно выполнить исполняемый файл. Когда nginx запущен, им можно управлять, вызывая исполняемый файл с параметром -s . Используйте следующий синтаксис:

Где сигнал может быть одним из нижеследующих:

  • stop — быстрое завершение
  • quit — плавное завершение
  • reload — перезагрузка конфигурационного файла
  • reopen — переоткрытие лог-файлов

Например, чтобы остановить процессы nginx с ожиданием окончания обслуживания текущих запросов рабочими процессами, можно выполнить следующую команду:

Команда должна быть выполнена под тем же пользователем, под которым был запущен nginx.

Изменения, сделанные в конфигурационном файле, не будут применены, пока команда перезагрузить конфигурацию не будет вручную отправлена nginx’у или он не будет перезапущен. Для перезагрузки конфигурации выполните:

Получив сигнал, главный процесс проверяет правильность синтаксиса нового конфигурационного файла и пытается применить конфигурацию, содержащуюся в нём. Если это ему удаётся, главный процесс запускает новые рабочие процессы и отправляет сообщения старым рабочим процессам с требованием завершиться. В противном случае, главный процесс откатывает изменения и продолжает работать со старой конфигурацией. Старые рабочие процессы, получив команду завершиться, прекращают принимать новые запросы и продолжают обслуживать текущие запросы до тех пор, пока все такие запросы не будут обслужены. После этого старые рабочие процессы завершаются.

Посылать сигналы процессам nginx можно также средствами Unix, такими как утилита kill . В этом случае сигнал отправляется напрямую процессу с данным ID. ID главного процесса nginx записывается по умолчанию в файл nginx.pid в каталоге /usr/local/nginx/logs или /var/run . Например, если ID главного процесса равен 1628, для отправки сигнала QUIT, который приведёт к плавному завершению nginx, нужно выполнить:

Для просмотра списка всех запущенных процессов nginx может быть использована утилита ps , например, следующим образом:

Дополнительную информацию об отправке сигналов процессам nginx можно найти в Управление nginx.

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

nginx состоит из модулей, которые настраиваются директивами, указанными в конфигурационном файле. Директивы делятся на простые и блочные. Простая директива состоит из имени и параметров, разделённых пробелами, и оканчивается точкой с запятой ( ; ). Блочная директива устроена так же, как и простая директива, но вместо точки с запятой после имени и параметров следует набор дополнительных инструкций, помещённых внутри фигурных скобок ( < и >). Если у блочной директивы внутри фигурных скобок можно задавать другие директивы, то она называется контекстом (примеры: events, http, server и location).

Директивы, помещённые в конфигурационном файле вне любого контекста, считаются находящимися в контексте main. Директивы events и http располагаются в контексте main , server — в http , а location — в server .

Часть строки после символа # считается комментарием.

Раздача статического содержимого

Одна из важных задач конфигурации nginx — раздача файлов, таких как изображения или статические HTML-страницы. Рассмотрим пример, в котором в зависимости от запроса файлы будут раздаваться из разных локальных каталогов: /data/www , который содержит HTML-файлы, и /data/images , содержащий файлы с изображениями. Для этого потребуется отредактировать конфигурационный файл и настроить блок server внутри блока http с двумя блоками location.

Во-первых, создайте каталог /data/www и положите в него файл index.html с любым текстовым содержанием, а также создайте каталог /data/images и положите в него несколько файлов с изображениями.

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

В общем случае конфигурационный файл может содержать несколько блоков server , различаемых по портам, на которых они слушают, и по имени сервера. Определив, какой server будет обрабатывать запрос, nginx сравнивает URI, указанный в заголовке запроса, с параметрами директив location , определённых внутри блока server .

В блок server добавьте блок location следующего вида:

Этот блок location задаёт “ / ” в качестве префикса, который сравнивается с URI из запроса. Для подходящих запросов добавлением URI к пути, указанному в директиве root, то есть, в данном случае, к /data/www , получается путь к запрашиваемому файлу в локальной файловой системе. Если есть совпадение с несколькими блоками location , nginx выбирает блок с самым длинным префиксом. В блоке location выше указан самый короткий префикс, длины один, и поэтому этот блок будет использован, только если не будет совпадения ни с одним из остальных блоков location .

Читайте также:  Невозможно изменить разрешение экрана windows

Далее, добавьте второй блок location :

Он будет давать совпадение с запросами, начинающимися с /images/ ( location / для них тоже подходит, но указанный там префикс короче).

Итоговая конфигурация блока server должна выглядеть следующим образом:

Это уже работающая конфигурация сервера, слушающего на стандартном порту 80 и доступного на локальном компьютере по адресу http://localhost/ . В ответ на запросы, URI которых начинаются с /images/ , сервер будет отправлять файлы из каталога /data/images . Например, на запрос http://localhost/images/example.png nginx отправит в ответ файл /data/images/example.png . Если же этот файл не существует, nginx отправит ответ, указывающий на ошибку 404. Запросы, URI которых не начинаются на /images/ , будут отображены на каталог /data/www . Например, в результате запроса http://localhost/some/example.html в ответ будет отправлен файл /data/www/some/example.html .

Чтобы применить новую конфигурацию, запустите nginx, если он ещё не запущен, или отправьте сигнал reload главному процессу nginx, выполнив:

В случае если что-то работает не как ожидалось, можно попытаться выяснить причину с помощью файлов access.log и error.log из каталога /usr/local/nginx/logs или /var/log/nginx .

Настройка простого прокси-сервера

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

Мы настроим базовый прокси-сервер, который будет обслуживать запросы изображений из локального каталога и отправлять все остальные запросы на проксируемый сервер. В этом примере оба сервера будут работать в рамках одного экземпляра nginx.

Во-первых, создайте проксируемый сервер, добавив ещё один блок server в конфигурационный файл nginx со следующим содержимым:

Это будет простой сервер, слушающий на порту 8080 (ранее директива listen не указывалась, потому что использовался стандартный порт 80) и отображающий все запросы на каталог /data/up1 в локальной файловой системе. Создайте этот каталог и положите в него файл index.html . Обратите внимание, что директива root помещена в контекст server . Такая директива root будет использована, когда директива location , выбранная для выполнения запроса, не содержит собственной директивы root .

Далее, используйте конфигурацию сервера из предыдущего раздела и видоизмените её, превратив в конфигурацию прокси-сервера. В первый блок location добавьте директиву proxy_pass, указав протокол, имя и порт проксируемого сервера в качестве параметра (в нашем случае это http://localhost:8080 ):

Мы изменим второй блок location , который на данный момент отображает запросы с префиксом /images/ на файлы из каталога /data/images так, чтобы он подходил для запросов изображений с типичными расширениями файлов. Изменённый блок location выглядит следующим образом:

Параметром является регулярное выражение, дающее совпадение со всеми URI, оканчивающимися на .gif , .jpg или .png . Регулярному выражению должен предшествовать символ

. Соответствующие запросы будут отображены на каталог /data/images .

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

Итоговая конфигурация прокси-сервера выглядит следующим образом:

Этот сервер будет фильтровать запросы, оканчивающиеся на .gif , .jpg или .png , и отображать их на каталог /data/images (добавлением URI к параметру директивы root ) и перенаправлять все остальные запросы на проксируемый сервер, сконфигурированный выше.

Чтобы применить новую конфигурацию, отправьте сигнал reload nginx’у, как описывалось в предыдущих разделах.

Существует множество других директив для дальнейшей настройки прокси-соединения.

Настройка проксирования FastCGI

nginx можно использовать для перенаправления запросов на FastCGI-серверы. На них могут исполняться приложения, созданные с использованием разнообразных фреймворков и языков программирования, например, PHP.

Базовая конфигурация nginx для работы с проксируемым FastCGI-сервером включает в себя использование директивы fastcgi_pass вместо директивы proxy_pass , и директив fastcgi_param для настройки параметров, передаваемых FastCGI-серверу. Представьте, что FastCGI-сервер доступен по адресу localhost:9000 . Взяв за основу конфигурацию прокси-сервера из предыдущего раздела, замените директиву proxy_pass на директиву fastcgi_pass и измените параметр на localhost:9000 . В PHP параметр SCRIPT_FILENAME используется для определения имени скрипта, а в параметре QUERY_STRING передаются параметры запроса. Получится следующая конфигурация:

Таким образом будет настроен сервер, который будет перенаправлять все запросы, кроме запросов статических изображений, на проксируемый сервер, работающий по адресу localhost:9000 , по протоколу FastCGI.

Источник

Beginner’s Guide

This guide gives a basic introduction to nginx and describes some simple tasks that can be done with it. It is supposed that nginx is already installed on the reader’s machine. If it is not, see the Installing nginx page. This guide describes how to start and stop nginx, and reload its configuration, explains the structure of the configuration file and describes how to set up nginx to serve out static content, how to configure nginx as a proxy server, and how to connect it with a FastCGI application.

nginx has one master process and several worker processes. The main purpose of the master process is to read and evaluate configuration, and maintain worker processes. Worker processes do actual processing of requests. nginx employs event-based model and OS-dependent mechanisms to efficiently distribute requests among worker processes. The number of worker processes is defined in the configuration file and may be fixed for a given configuration or automatically adjusted to the number of available CPU cores (see worker_processes).

Читайте также:  Не показывает панель управления нвидиа windows 10

The way nginx and its modules work is determined in the configuration file. By default, the configuration file is named nginx.conf and placed in the directory /usr/local/nginx/conf , /etc/nginx , or /usr/local/etc/nginx .

Starting, Stopping, and Reloading Configuration

To start nginx, run the executable file. Once nginx is started, it can be controlled by invoking the executable with the -s parameter. Use the following syntax:

Where signal may be one of the following:

  • stop — fast shutdown
  • quit — graceful shutdown
  • reload — reloading the configuration file
  • reopen — reopening the log files

For example, to stop nginx processes with waiting for the worker processes to finish serving current requests, the following command can be executed:

This command should be executed under the same user that started nginx.

Changes made in the configuration file will not be applied until the command to reload configuration is sent to nginx or it is restarted. To reload configuration, execute:

Once the master process receives the signal to reload configuration, it checks the syntax validity of the new configuration file and tries to apply the configuration provided in it. If this is a success, the master process starts new worker processes and sends messages to old worker processes, requesting them to shut down. Otherwise, the master process rolls back the changes and continues to work with the old configuration. Old worker processes, receiving a command to shut down, stop accepting new connections and continue to service current requests until all such requests are serviced. After that, the old worker processes exit.

A signal may also be sent to nginx processes with the help of Unix tools such as the kill utility. In this case a signal is sent directly to a process with a given process ID. The process ID of the nginx master process is written, by default, to the nginx.pid in the directory /usr/local/nginx/logs or /var/run . For example, if the master process ID is 1628, to send the QUIT signal resulting in nginx’s graceful shutdown, execute:

For getting the list of all running nginx processes, the ps utility may be used, for example, in the following way:

For more information on sending signals to nginx, see Controlling nginx.

Configuration File’s Structure

nginx consists of modules which are controlled by directives specified in the configuration file. Directives are divided into simple directives and block directives. A simple directive consists of the name and parameters separated by spaces and ends with a semicolon ( ; ). A block directive has the same structure as a simple directive, but instead of the semicolon it ends with a set of additional instructions surrounded by braces ( < and >). If a block directive can have other directives inside braces, it is called a context (examples: events, http, server, and location).

Directives placed in the configuration file outside of any contexts are considered to be in the main context. The events and http directives reside in the main context, server in http , and location in server .

The rest of a line after the # sign is considered a comment.

Serving Static Content

An important web server task is serving out files (such as images or static HTML pages). You will implement an example where, depending on the request, files will be served from different local directories: /data/www (which may contain HTML files) and /data/images (containing images). This will require editing of the configuration file and setting up of a server block inside the http block with two location blocks.

First, create the /data/www directory and put an index.html file with any text content into it and create the /data/images directory and place some images in it.

Next, open the configuration file. The default configuration file already includes several examples of the server block, mostly commented out. For now comment out all such blocks and start a new server block:

Generally, the configuration file may include several server blocks distinguished by ports on which they listen to and by server names. Once nginx decides which server processes a request, it tests the URI specified in the request’s header against the parameters of the location directives defined inside the server block.

Add the following location block to the server block:

This location block specifies the “ / ” prefix compared with the URI from the request. For matching requests, the URI will be added to the path specified in the root directive, that is, to /data/www , to form the path to the requested file on the local file system. If there are several matching location blocks nginx selects the one with the longest prefix. The location block above provides the shortest prefix, of length one, and so only if all other location blocks fail to provide a match, this block will be used.

Читайте также:  Mac os psql client install

Next, add the second location block:

It will be a match for requests starting with /images/ ( location / also matches such requests, but has shorter prefix).

The resulting configuration of the server block should look like this:

This is already a working configuration of a server that listens on the standard port 80 and is accessible on the local machine at http://localhost/ . In response to requests with URIs starting with /images/ , the server will send files from the /data/images directory. For example, in response to the http://localhost/images/example.png request nginx will send the /data/images/example.png file. If such file does not exist, nginx will send a response indicating the 404 error. Requests with URIs not starting with /images/ will be mapped onto the /data/www directory. For example, in response to the http://localhost/some/example.html request nginx will send the /data/www/some/example.html file.

To apply the new configuration, start nginx if it is not yet started or send the reload signal to the nginx’s master process, by executing:

In case something does not work as expected, you may try to find out the reason in access.log and error.log files in the directory /usr/local/nginx/logs or /var/log/nginx .

Setting Up a Simple Proxy Server

One of the frequent uses of nginx is setting it up as a proxy server, which means a server that receives requests, passes them to the proxied servers, retrieves responses from them, and sends them to the clients.

We will configure a basic proxy server, which serves requests of images with files from the local directory and sends all other requests to a proxied server. In this example, both servers will be defined on a single nginx instance.

First, define the proxied server by adding one more server block to the nginx’s configuration file with the following contents:

This will be a simple server that listens on the port 8080 (previously, the listen directive has not been specified since the standard port 80 was used) and maps all requests to the /data/up1 directory on the local file system. Create this directory and put the index.html file into it. Note that the root directive is placed in the server context. Such root directive is used when the location block selected for serving a request does not include own root directive.

Next, use the server configuration from the previous section and modify it to make it a proxy server configuration. In the first location block, put the proxy_pass directive with the protocol, name and port of the proxied server specified in the parameter (in our case, it is http://localhost:8080 ):

We will modify the second location block, which currently maps requests with the /images/ prefix to the files under the /data/images directory, to make it match the requests of images with typical file extensions. The modified location block looks like this:

The parameter is a regular expression matching all URIs ending with .gif , .jpg , or .png . A regular expression should be preceded with

. The corresponding requests will be mapped to the /data/images directory.

When nginx selects a location block to serve a request it first checks location directives that specify prefixes, remembering location with the longest prefix, and then checks regular expressions. If there is a match with a regular expression, nginx picks this location or, otherwise, it picks the one remembered earlier.

The resulting configuration of a proxy server will look like this:

This server will filter requests ending with .gif , .jpg , or .png and map them to the /data/images directory (by adding URI to the root directive’s parameter) and pass all other requests to the proxied server configured above.

To apply new configuration, send the reload signal to nginx as described in the previous sections.

There are many more directives that may be used to further configure a proxy connection.

Setting Up FastCGI Proxying

nginx can be used to route requests to FastCGI servers which run applications built with various frameworks and programming languages such as PHP.

The most basic nginx configuration to work with a FastCGI server includes using the fastcgi_pass directive instead of the proxy_pass directive, and fastcgi_param directives to set parameters passed to a FastCGI server. Suppose the FastCGI server is accessible on localhost:9000 . Taking the proxy configuration from the previous section as a basis, replace the proxy_pass directive with the fastcgi_pass directive and change the parameter to localhost:9000 . In PHP, the SCRIPT_FILENAME parameter is used for determining the script name, and the QUERY_STRING parameter is used to pass request parameters. The resulting configuration would be:

This will set up a server that will route all requests except for requests for static images to the proxied server operating on localhost:9000 through the FastCGI protocol.

Источник

Оцените статью