Error page 404 fallback

Эта директива появилась в версии 1.11.8.

Директивы

Синтаксис: absolute_redirect on | off;
Умолчание:
absolute_redirect on;
Контекст: http, server, location

Эта директива появилась в версии 1.11.8.

Если запрещено, то перенаправления, выдаваемые nginx’ом, будут относительными.

См. также директивы server_name_in_redirect
и port_in_redirect.

Синтаксис: aio
on |
off |
threads[=pool];
Умолчание:
aio off;
Контекст: http, server, location

Эта директива появилась в версии 0.8.11.

Разрешает или запрещает использование файлового асинхронного ввода-вывода (AIO)
во FreeBSD и Linux:

location /video/ {
    aio            on;
    output_buffers 1 64k;
}

Во FreeBSD AIO можно использовать, начиная с FreeBSD 4.3.
До FreeBSD 11.0
AIO можно либо собрать в ядре статически:

options VFS_AIO

либо загрузить динамически через загружаемый модуль ядра:

kldload aio

В Linux AIO можно использовать только начиная с версии ядра 2.6.22.
Кроме того, необходимо также дополнительно включить
directio,
иначе чтение будет блокирующимся:

location /video/ {
    aio            on;
    directio       512;
    output_buffers 1 128k;
}

В Linux
directio
можно использовать только для чтения блоков, выравненных
на границу 512 байт (или 4К для XFS).
Невыравненный конец файла будет читаться блокированно.
То же относится к запросам с указанием диапазона запрашиваемых байт
(byte-range requests) и к запросам FLV не с начала файла: чтение
невыравненных начала и конца ответа будет блокирующимся.

При одновременном включении AIO и sendfile в Linux
для файлов, размер которых больше либо равен указанному
в директиве directio, будет использоваться AIO,
а для файлов меньшего размера
или при выключенном directio — sendfile:

location /video/ {
    sendfile       on;
    aio            on;
    directio       8m;
}

Кроме того, читать и отправлять
файлы можно в многопоточном режиме (1.7.11),
не блокируя при этом рабочий процесс:

location /video/ {
    sendfile       on;
    aio            threads;
}

Операции чтения или отправки файлов будут обрабатываться потоками из указанного
пула.
Если пул потоков не задан явно,
используется пул с именем “default”.
Имя пула может быть задано при помощи переменных:

aio threads=pool$disk;

По умолчанию поддержка многопоточности выключена, её сборку следует
разрешить с помощью конфигурационного параметра
--with-threads.
В настоящий момент многопоточность совместима только с методами
epoll,
kqueue
и
eventport.
Отправка файлов в многопоточном режиме поддерживается только на Linux.

См. также директиву sendfile.

Синтаксис: aio_write on | off;
Умолчание:
aio_write off;
Контекст: http, server, location

Эта директива появилась в версии 1.9.13.

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

Синтаксис: alias путь;
Умолчание:

Контекст: location

Задаёт замену для указанного location’а.
Например, при такой конфигурации

location /i/ {
    alias /data/w3/images/;
}

на запрос
/i/top.gif” будет отдан файл
/data/w3/images/top.gif.

В значении параметра путь можно использовать переменные,
кроме $document_root и $realpath_root.

Если alias используется внутри location’а, заданного
регулярным выражением, то регулярное выражение должно содержать
выделения, а сам alias — ссылки на эти выделения
(0.7.40), например:

location ~ ^/users/(.+.(?:gif|jpe?g|png))$ {
    alias /data/w3/images/$1;
}

Если location и последняя часть значения директивы совпадают:

location /images/ {
    alias /data/w3/images/;
}

то лучше воспользоваться директивой
root:

location /images/ {
    root /data/w3;
}
Синтаксис: auth_delay время;
Умолчание:
auth_delay 0s;
Контекст: http, server, location

Эта директива появилась в версии 1.17.10.

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

Синтаксис: chunked_transfer_encoding on | off;
Умолчание:
chunked_transfer_encoding on;
Контекст: http, server, location

Позволяет запретить формат передачи данных частями (chunked transfer
encoding) в HTTP/1.1.
Это может понадобиться при использовании программ, не поддерживающих
chunked encoding, несмотря на требования стандарта.

Синтаксис: client_body_buffer_size размер;
Умолчание:
client_body_buffer_size 8k|16k;
Контекст: http, server, location

Задаёт размер буфера для чтения тела запроса клиента.
Если тело запроса больше заданного буфера,
то всё тело запроса или только его часть записывается во
временный файл.
По умолчанию размер одного буфера равен двум размерам страницы.
На x86, других 32-битных платформах и x86-64 это 8K.
На других 64-битных платформах это обычно 16K.

Синтаксис: client_body_in_file_only
on |
clean |
off;
Умолчание:
client_body_in_file_only off;
Контекст: http, server, location

Определяет, сохранять ли всё тело запроса клиента в файл.
Директиву можно использовать для отладки и при использовании переменной
$request_body_file
или метода
$r->request_body_file
модуля
ngx_http_perl_module.

При установке значения on временные файлы
по окончании обработки запроса не удаляются.

Значение clean разрешает удалять временные файлы,
оставшиеся по окончании обработки запроса.

Синтаксис: client_body_in_single_buffer on | off;
Умолчание:
client_body_in_single_buffer off;
Контекст: http, server, location

Определяет, сохранять ли всё тело запроса клиента в одном буфере.
Директива рекомендуется при использовании переменной
$request_body
для уменьшения требуемого числа операций копирования.

Синтаксис: client_body_temp_path
путь
[уровень1
[уровень2
[уровень3]]];
Умолчание:
client_body_temp_path client_body_temp;
Контекст: http, server, location

Задаёт каталог для хранения временных файлов с телами запросов клиентов.
В каталоге может использоваться иерархия подкаталогов до трёх уровней.
Например, при такой конфигурации

client_body_temp_path /spool/nginx/client_temp 1 2;

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

/spool/nginx/client_temp/7/45/00000123457
Синтаксис: client_body_timeout время;
Умолчание:
client_body_timeout 60s;
Контекст: http, server, location

Задаёт таймаут при чтении тела запроса клиента.
Таймаут устанавливается не на всю передачу тела запроса,
а только между двумя последовательными операциями чтения.
Если по истечении этого времени клиент ничего не передаст,
обработка запроса прекращается с ошибкой
408 (Request Time-out).

Синтаксис: client_header_buffer_size размер;
Умолчание:
client_header_buffer_size 1k;
Контекст: http, server

Задаёт размер буфера для чтения заголовка запроса клиента.
Для большинства запросов достаточно буфера размером в 1K байт.
Однако если в запросе есть длинные cookies, или же запрос
пришёл от WAP-клиента, то он может не поместиться в 1K.
Поэтому, если строка запроса или поле заголовка запроса
не помещаются полностью в этот буфер, то выделяются буферы
большего размера, задаваемые директивой
large_client_header_buffers.

Если директива указана на уровне server,
то может использоваться значение из сервера по умолчанию.
Подробнее см. в разделе
“Выбор
виртуального сервера”.

Синтаксис: client_header_timeout время;
Умолчание:
client_header_timeout 60s;
Контекст: http, server

Задаёт таймаут при чтении заголовка запроса клиента.
Если по истечении этого времени клиент не передаст полностью заголовок,
обработка запроса прекращается с ошибкой
408 (Request Time-out).

Синтаксис: client_max_body_size размер;
Умолчание:
client_max_body_size 1m;
Контекст: http, server, location

Задаёт максимально допустимый размер тела запроса клиента.
Если размер больше заданного, то клиенту возвращается ошибка
413 (Request Entity Too Large).
Следует иметь в виду, что
браузеры не умеют корректно показывать
эту ошибку.
Установка параметра размер в 0 отключает
проверку размера тела запроса клиента.

Синтаксис: connection_pool_size размер;
Умолчание:
connection_pool_size 256|512;
Контекст: http, server

Позволяет производить точную настройку выделения памяти
под конкретные соединения.
Эта директива не оказывает существенного влияния на
производительность, и её не следует использовать.
По умолчанию размер равен
256 байт на 32-битных платформах и 512 байт на 64-битных платформах.

До версии 1.9.8 по умолчанию использовалось значение 256 на всех платформах.

Синтаксис: default_type mime-тип;
Умолчание:
default_type text/plain;
Контекст: http, server, location

Задаёт MIME-тип ответов по умолчанию.
Соответствие расширений имён файлов MIME-типу ответов задаётся
с помощью директивы types.

Синтаксис: directio размер | off;
Умолчание:
directio off;
Контекст: http, server, location

Эта директива появилась в версии 0.7.7.

Разрешает использовать флаги
O_DIRECT (FreeBSD, Linux),
F_NOCACHE (macOS)
или функцию directio() (Solaris)
при чтении файлов, размер которых больше либо равен указанному.
Директива автоматически запрещает (0.7.15) использование
sendfile
для данного запроса.
Рекомендуется использовать для больших файлов:

directio 4m;

или при использовании aio в Linux.

Синтаксис: directio_alignment размер;
Умолчание:
directio_alignment 512;
Контекст: http, server, location

Эта директива появилась в версии 0.8.11.

Устанавливает выравнивание для
directio.
В большинстве случаев достаточно 512-байтового выравнивания, однако
при использовании XFS под Linux его нужно увеличить до 4K.

Синтаксис: disable_symlinks off;
disable_symlinks
on |
if_not_owner
[from=часть];
Умолчание:
disable_symlinks off;
Контекст: http, server, location

Эта директива появилась в версии 1.1.15.

Определяет, как следует поступать с символическими ссылками
при открытии файлов:

off
Символические ссылки в пути допускаются и не проверяются.
Это стандартное поведение.
on
Если любой компонент пути является символической ссылкой,
доступ к файлу запрещается.
if_not_owner
Доступ к файлу запрещается, если любой компонент пути
является символической ссылкой, а ссылка и объект, на
который она ссылается, имеют разных владельцев.
from=часть
При проверке символических ссылок
(параметры on и if_not_owner)
обычно проверяются все компоненты пути.
Можно не проверять символические ссылки в начальной части пути,
указав дополнительно параметр
from=часть.
В этом случае символические ссылки проверяются лишь начиная
с компонента пути, который следует за заданной начальной частью.
Если значение не является начальной частью проверяемого пути,
путь проверяется целиком, как если бы этот параметр не был указан вовсе.
Если значение целиком совпадает с именем файла,
символические ссылки не проверяются.
В значении параметра можно использовать переменные.

Пример:

disable_symlinks on from=$document_root;

Эта директива доступна только на системах, в которых есть
интерфейсы openat() и fstatat().
К таким системам относятся современные версии FreeBSD, Linux и Solaris.

Параметры on и if_not_owner
требуют дополнительных затрат на обработку.

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

Модули
ngx_http_autoindex_module,
ngx_http_random_index_module
и ngx_http_dav_module
в настоящий момент игнорируют эту директиву.

Синтаксис: error_page
код ...
[=[ответ]]
uri;
Умолчание:

Контекст: http, server, location, if в location

Задаёт URI, который будет показываться для указанных ошибок.
В значении uri можно использовать переменные.

Пример:

error_page 404             /404.html;
error_page 500 502 503 504 /50x.html;

При этом делается внутреннее перенаправление на указанный uri,
а метод запроса клиента меняется на “GET
(для всех методов, отличных от
GET” и “HEAD”).

Кроме того, можно поменять код ответа на другой,
используя синтаксис вида “=ответ”, например:

error_page 404 =200 /empty.gif;

Если ошибочный ответ обрабатывается проксированным сервером или
FastCGI/uwsgi/SCGI/gRPC-сервером,
и этот сервер может вернуть разные коды ответов,
например, 200, 302, 401 или 404, то можно выдавать возвращаемый им код:

error_page 404 = /404.php;

Если при внутреннем перенаправлении не нужно менять URI и метод,
то можно передать обработку ошибки в именованный location:

location / {
    error_page 404 = @fallback;
}

location @fallback {
    proxy_pass http://backend;
}

Если при обработке uri происходит ошибка,
клиенту возвращается ответ с кодом последней случившейся ошибки.

Также существует возможность использовать перенаправления URL для обработки
ошибок:

error_page 403      http://example.com/forbidden.html;
error_page 404 =301 http://example.com/notfound.html;

В этом случае по умолчанию клиенту возвращается код ответа 302.
Его можно изменить только на один из кодов ответа, относящихся к
перенаправлениям (301, 302, 303, 307 и 308).

До версий 1.1.16 и 1.0.13 код 307 не обрабатывался как перенаправление.

До версии 1.13.0 код 308 не обрабатывался как перенаправление.

Директивы наследуются с предыдущего уровня конфигурации при условии, что
на данном уровне не описаны свои директивы error_page.

Синтаксис: etag on | off;
Умолчание:
etag on;
Контекст: http, server, location

Эта директива появилась в версии 1.3.3.

Разрешает или запрещает автоматическую генерацию поля “ETag”
заголовка ответа для статических ресурсов.

Синтаксис: http { ... }
Умолчание:

Контекст: main

Предоставляет контекст конфигурационного файла, в котором указываются
директивы HTTP-сервера.

Синтаксис: if_modified_since
off |
exact |
before;
Умолчание:
if_modified_since exact;
Контекст: http, server, location

Эта директива появилась в версии 0.7.24.

Определяет, как сравнивать время модификации ответа с
временем в поле
“If-Modified-Since”
заголовка запроса:

off
ответ всегда считается изменившимся (0.7.34);
exact
точное совпадение;
before
время модификации ответа меньше или равно времени, заданному в поле
“If-Modified-Since” заголовка запроса.
Синтаксис: ignore_invalid_headers on | off;
Умолчание:
ignore_invalid_headers on;
Контекст: http, server

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

Если директива указана на уровне server,
то может использоваться значение из сервера по умолчанию.
Подробнее см. в разделе
“Выбор
виртуального сервера”.

Синтаксис: internal;
Умолчание:

Контекст: location

Указывает, что location может использоваться только для внутренних запросов.
Для внешних запросов клиенту будет возвращаться ошибка
404 (Not Found).
Внутренними запросами являются:

  • запросы, перенаправленные директивами
    error_page,
    index,
    random_index и
    try_files;
  • запросы, перенаправленные с помощью поля
    “X-Accel-Redirect” заголовка ответа вышестоящего сервера;
  • подзапросы, формируемые командой
    include virtual
    модуля
    ngx_http_ssi_module,
    директивами модуля
    ngx_http_addition_module,
    а также директивами
    auth_request и
    mirror;

  • запросы, изменённые директивой
    rewrite.

Пример:

error_page 404 /404.html;

location = /404.html {
    internal;
}

Для предотвращения зацикливания, которое может возникнуть при
использовании некорректных конфигураций, количество внутренних
перенаправлений ограничено десятью.
По достижении этого ограничения будет возвращена ошибка
500 (Internal Server Error).
В таком случае в лог-файле ошибок можно увидеть сообщение
“rewrite or internal redirection cycle”.

Синтаксис: keepalive_disable none | браузер ...;
Умолчание:
keepalive_disable msie6;
Контекст: http, server, location

Запрещает keep-alive соединения с некорректно ведущими себя браузерами.
Параметры браузер указывают, на какие браузеры это
распространяется.
Значение msie6 запрещает keep-alive соединения
со старыми версиями MSIE после получения запроса POST.
Значение safari запрещает keep-alive соединения
с Safari и подобными им браузерами на macOS и подобных ей ОС.
Значение none разрешает keep-alive соединения
со всеми браузерами.

До версии 1.1.18 под значение safari подпадали
все Safari и подобные им браузеры на всех ОС, и keep-alive
соединения с ними были по умолчанию запрещены.

Синтаксис: keepalive_requests число;
Умолчание:
keepalive_requests 1000;
Контекст: http, server, location

Эта директива появилась в версии 0.8.0.

Задаёт максимальное число запросов, которые можно
сделать по одному keep-alive соединению.
После того, как сделано максимальное число запросов,
соединение закрывается.

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

До версии 1.19.10 по умолчанию использовалось значение 100.

Синтаксис: keepalive_time время;
Умолчание:
keepalive_time 1h;
Контекст: http, server, location

Эта директива появилась в версии 1.19.10.

Ограничивает максимальное время, в течение которого
могут обрабатываться запросы в рамках keep-alive соединения.
По достижении заданного времени соединение закрывается
после обработки очередного запроса.

Синтаксис: keepalive_timeout
таймаут
[заголовок_таймаута];
Умолчание:
keepalive_timeout 75s;
Контекст: http, server, location

Первый параметр задаёт таймаут, в течение которого keep-alive
соединение с клиентом не будет закрыто со стороны сервера.
Значение 0 запрещает keep-alive соединения с клиентами.
Второй необязательный параметр задаёт значение в поле
“Keep-Alive: timeout=время
заголовка ответа.
Два параметра могут отличаться друг от друга.

Поле
“Keep-Alive: timeout=время
заголовка понимают Mozilla и Konqueror.
MSIE сам закрывает keep-alive соединение примерно через 60 секунд.

Синтаксис: large_client_header_buffers число размер;
Умолчание:
large_client_header_buffers 4 8k;
Контекст: http, server

Задаёт максимальное число и размер
буферов для чтения большого заголовка запроса клиента.
Строка запроса не должна превышать размера одного буфера, иначе клиенту
возвращается ошибка
414 (Request-URI Too Large).
Поле заголовка запроса также не должно превышать размера одного буфера,
иначе клиенту возвращается ошибка
400 (Bad Request).
Буферы выделяются только по мере необходимости.
По умолчанию размер одного буфера равен 8K байт.
Если по окончании обработки запроса соединение переходит в состояние
keep-alive, эти буферы освобождаются.

Если директива указана на уровне server,
то может использоваться значение из сервера по умолчанию.
Подробнее см. в разделе
“Выбор
виртуального сервера”.

Синтаксис: limit_except метод ... { ... }
Умолчание:

Контекст: location

Ограничивает HTTP-методы, доступные внутри location.
Параметр метод может быть одним из
GET,
HEAD,
POST,
PUT,
DELETE,
MKCOL,
COPY,
MOVE,
OPTIONS,
PROPFIND,
PROPPATCH,
LOCK,
UNLOCK
или
PATCH.
Если разрешён метод GET, то метод
HEAD также будет разрешён.
Доступ к остальным методам может быть ограничен при помощи директив модулей
ngx_http_access_module,
ngx_http_auth_basic_module
и
ngx_http_auth_jwt_module
(1.13.10):

limit_except GET {
    allow 192.168.1.0/32;
    deny  all;
}

Обратите внимание, что данное ограничение действует для всех методов,
кроме GET и HEAD.

Синтаксис: limit_rate скорость;
Умолчание:
limit_rate 0;
Контекст: http, server, location, if в location

Ограничивает скорость передачи ответа клиенту.
Скорость задаётся в байтах в секунду.
Значение 0 отключает ограничение скорости.

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

В значении параметра можно использовать переменные (1.17.0).
Это может быть полезно в случаях, когда скорость нужно ограничивать
в зависимости от какого-либо условия:

map $slow $rate {
    1     4k;
    2     8k;
}

limit_rate $rate;

Ограничение скорости можно также задать в переменной
$limit_rate,
однако начиная с 1.17.0 использовать данный метод не рекомендуется:

server {

    if ($slow) {
        set $limit_rate 4k;
    }

    ...
}

Кроме того, ограничение скорости может быть задано в поле
“X-Accel-Limit-Rate” заголовка ответа проксированного сервера.
Эту возможность можно запретить с помощью директив
proxy_ignore_headers,
fastcgi_ignore_headers,
uwsgi_ignore_headers
и
scgi_ignore_headers.

Синтаксис: limit_rate_after размер;
Умолчание:
limit_rate_after 0;
Контекст: http, server, location, if в location

Эта директива появилась в версии 0.8.0.

Задаёт начальный объём данных, после передачи которого начинает
ограничиваться скорость передачи ответа клиенту.
В значении параметра можно использовать переменные (1.17.0).

Пример:

location /flv/ {
    flv;
    limit_rate_after 500k;
    limit_rate       50k;
}
Синтаксис: lingering_close
off |
on |
always;
Умолчание:
lingering_close on;
Контекст: http, server, location

Эта директива появилась в версиях 1.1.0 и 1.0.6.

Управляет закрытием соединений с клиентами.

Со значением по умолчанию “on” nginx будет
ждать и
обрабатывать дополнительные данные,
поступающие от клиента, перед полным закрытием соединения, но только
если эвристика указывает на то, что клиент может ещё послать данные.

Со значением “always” nginx всегда будет
ждать и обрабатывать дополнительные данные, поступающие от клиента.

Со значением “off” nginx не будет ждать поступления
дополнительных данных и сразу же закроет соединение.
Это поведение нарушает протокол и поэтому не должно использоваться без
необходимости.

Для управления закрытием
HTTP/2-соединений
директива должна быть задана на уровне server (1.19.1).

Синтаксис: lingering_time время;
Умолчание:
lingering_time 30s;
Контекст: http, server, location

Если действует lingering_close,
эта директива задаёт максимальное время, в течение которого nginx
будет обрабатывать (читать и игнорировать) дополнительные данные,
поступающие от клиента.
По прошествии этого времени соединение будет закрыто, даже если
будут ещё данные.

Синтаксис: lingering_timeout время;
Умолчание:
lingering_timeout 5s;
Контекст: http, server, location

Если действует lingering_close, эта директива задаёт
максимальное время ожидания поступления дополнительных данных от клиента.
Если в течение этого времени данные не были получены, соединение закрывается.
В противном случае данные читаются и игнорируются, и nginx снова
ждёт поступления данных.
Цикл “ждать-читать-игнорировать” повторяется, но не дольше чем задано
директивой lingering_time.

Синтаксис: listen
адрес[:порт]
[default_server]
[ssl]
[http2 | spdy]
[proxy_protocol]
[setfib=число]
[fastopen=число]
[backlog=число]
[rcvbuf=размер]
[sndbuf=размер]
[accept_filter=фильтр]
[deferred]
[bind]
[ipv6only=on|off]
[reuseport]
[so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];

listen
порт
[default_server]
[ssl]
[http2 | spdy]
[proxy_protocol]
[setfib=число]
[fastopen=число]
[backlog=число]
[rcvbuf=размер]
[sndbuf=размер]
[accept_filter=фильтр]
[deferred]
[bind]
[ipv6only=on|off]
[reuseport]
[so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];

listen
unix:путь
[default_server]
[ssl]
[http2 | spdy]
[proxy_protocol]
[backlog=число]
[rcvbuf=размер]
[sndbuf=размер]
[accept_filter=фильтр]
[deferred]
[bind]
[so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
Умолчание:
listen *:80 | *:8000;
Контекст: server

Задаёт адрес и порт для IP
или путь для UNIX-сокета,
на которых сервер будет принимать запросы.
Можно указать адрес и порт,
либо только адрес или только порт.
Кроме того, адрес может быть именем хоста, например:

listen 127.0.0.1:8000;
listen 127.0.0.1;
listen 8000;
listen *:8000;
listen localhost:8000;

IPv6-адреса (0.7.36) задаются в квадратных скобках:

listen [::]:8000;
listen [::1];

UNIX-сокеты (0.8.21) задаются при помощи префикса “unix:”:

listen unix:/var/run/nginx.sock;

Если указан только адрес, то используется порт 80.

Если директива не указана, то используется либо *:80,
если nginx работает с привилегиями суперпользователя,
либо *:8000.

Если у директивы есть параметр default_server, то сервер,
в котором описана эта директива, будет сервером по умолчанию для указанной пары
адрес:порт.
Если же директив с параметром default_server нет, то
сервером по умолчанию будет первый сервер, в котором описана пара
адрес:порт.

До версии 0.8.21 этот параметр назывался просто
default.

Параметр ssl (0.7.14) указывает на то, что все соединения,
принимаемые на данном порту, должны работать в режиме SSL.
Это позволяет задать компактную конфигурацию для сервера,
работающего сразу в двух режимах — HTTP и HTTPS.

Параметр http2 (1.9.5) позволяет принимать на этом порту
HTTP/2-соединения.
Обычно, чтобы это работало, следует также указать параметр
ssl, однако nginx можно также настроить и на приём
HTTP/2-соединений без SSL.

Параметр spdy (1.3.15-1.9.4) позволяет принимать на этом порту
SPDY-соединения.
Обычно, чтобы это работало, следует также указать параметр
ssl, однако nginx можно также настроить и на приём
SPDY-соединений без SSL.

Параметр proxy_protocol (1.5.12)
указывает на то, что все соединения, принимаемые на данном порту,
должны использовать
протокол
PROXY.

Протокол PROXY версии 2 поддерживается начиная с версии 1.13.11.

В директиве listen можно также указать несколько
дополнительных параметров, специфичных для связанных с сокетами
системных вызовов.
Эти параметры можно задать в любой директиве listen,
но только один раз для указанной пары
адрес:порт.

До версии 0.8.21 их можно было указывать лишь в директиве
listen совместно с параметром default.

setfib=число
этот параметр (0.8.44) задаёт таблицу маршрутизации, FIB
(параметр SO_SETFIB) для слушающего сокета.
В настоящий момент это работает только на FreeBSD.
fastopen=число
включает
“TCP Fast Open”
для слушающего сокета (1.5.8) и
ограничивает
максимальную длину очереди соединений, которые ещё не завершили процесс
three-way handshake.

Не включайте “TCP Fast Open”, не убедившись, что сервер может адекватно
обрабатывать многократное получение

одного и того же SYN-пакета с данными.

backlog=число
задаёт параметр backlog в вызове
listen(), который ограничивает
максимальный размер очереди ожидающих приёма соединений.
По умолчанию backlog устанавливается равным -1 для
FreeBSD, DragonFly BSD и macOS, и 511 для других платформ.
rcvbuf=размер
задаёт размер буфера приёма
(параметр SO_RCVBUF) для слушающего сокета.
sndbuf=размер
задаёт размер буфера передачи
(параметр SO_SNDBUF) для слушающего сокета.
accept_filter=фильтр
задаёт название accept-фильтра
(параметр SO_ACCEPTFILTER) для слушающего сокета,
который включается для фильтрации входящих соединений
перед передачей их в accept().
Работает только на FreeBSD и NetBSD 5.0+.
Можно использовать два фильтра:
dataready
и
httpready.
deferred
указывает использовать отложенный accept()
(параметр TCP_DEFER_ACCEPT сокета) на Linux.
bind
указывает, что для данной пары
адрес:порт нужно делать
bind() отдельно.
Это нужно потому, что если описаны несколько директив listen
с одинаковым портом, но разными адресами, и одна из директив
listen слушает на всех адресах для данного порта
(*:порт), то nginx сделает
bind() только на *:порт.
Необходимо заметить, что в этом случае для определения адреса, на который
пришло соединение, делается системный вызов getsockname().
Если же используются параметры setfib,
fastopen,
backlog, rcvbuf,
sndbuf, accept_filter,
deferred, ipv6only,
reuseport
или so_keepalive,
то для данной пары
адрес:порт всегда делается
отдельный вызов bind().
ipv6only=on|off
этот параметр (0.7.42) определяет
(через параметр сокета IPV6_V6ONLY),
будет ли слушающий на wildcard-адресе [::] IPv6-сокет
принимать только IPv6-соединения, или же одновременно IPv6- и IPv4-соединения.
По умолчанию параметр включён.
Установить его можно только один раз на старте.

До версии 1.3.4,
если этот параметр не был задан явно, то для сокета действовали
настройки операционной системы.

reuseport
этот параметр (1.9.1) указывает, что нужно создавать отдельный слушающий сокет
для каждого рабочего процесса
(через параметр сокета
SO_REUSEPORT для Linux 3.9+ и DragonFly BSD
или SO_REUSEPORT_LB для FreeBSD 12+), позволяя ядру
распределять входящие соединения между рабочими процессами.
В настоящий момент это работает только на Linux 3.9+, DragonFly BSD
и FreeBSD 12+ (1.15.1).

Ненадлежащее использование параметра может быть
небезопасно.

so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]
этот параметр (1.1.11) конфигурирует для слушающего сокета
поведение “TCP keepalive”.
Если этот параметр опущен, то для сокета будут действовать
настройки операционной системы.
Если он установлен в значение “on”, то для сокета
включается параметр SO_KEEPALIVE.
Если он установлен в значение “off”, то для сокета
параметр SO_KEEPALIVE выключается.
Некоторые операционные системы поддерживают настройку параметров
“TCP keepalive” на уровне сокета посредством параметров
TCP_KEEPIDLE, TCP_KEEPINTVL и
TCP_KEEPCNT.
На таких системах (в настоящий момент это Linux 2.4+, NetBSD 5+ и
FreeBSD 9.0-STABLE)
их можно сконфигурировать с помощью параметров keepidle,
keepintvl и keepcnt.
Один или два параметра могут быть опущены, в таком случае для
соответствующего параметра сокета будут действовать стандартные
системные настройки.
Например,

so_keepalive=30m::10

установит таймаут бездействия (TCP_KEEPIDLE) в 30 минут,
для интервала проб (TCP_KEEPINTVL) будет действовать
стандартная системная настройка, а счётчик проб (TCP_KEEPCNT)
будет равен 10.

Пример:

listen 127.0.0.1 default_server accept_filter=dataready backlog=1024;
Синтаксис: location [
= |
~ |
~* |
^~
] uri { ... }

location @имя { ... }
Умолчание:

Контекст: server, location

Устанавливает конфигурацию в зависимости от URI запроса.

Для сопоставления используется URI запроса в нормализованном виде,
после декодирования текста, заданного в виде “%XX”,
преобразования относительных элементов пути “.” и
..” в реальные и возможной
замены двух и более подряд идущих
слэшей на один.

location можно задать префиксной строкой или регулярным выражением.
Регулярные выражения задаются либо с модификатором “~*
(для поиска совпадения без учёта регистра символов),
либо с модификатором “~” (с учётом регистра).
Чтобы найти location, соответствующий запросу, вначале проверяются
location’ы, заданные префиксными строками (префиксные location’ы).
Среди них ищется location с совпадающим префиксом
максимальной длины и запоминается.
Затем проверяются регулярные выражения, в порядке их следования
в конфигурационном файле.
Проверка регулярных выражений прекращается после первого же совпадения,
и используется соответствующая конфигурация.
Если совпадение с регулярным выражением не найдено, то используется
конфигурация запомненного ранее префиксного location’а.

Блоки location могут быть вложенными,
с некоторыми исключениями, о которых говорится ниже.

Для операционных систем, нечувствительных к регистру символов, таких
как macOS и Cygwin, сравнение с префиксными строками производится
без учёта регистра (0.7.7).
Однако сравнение ограничено только однобайтными locale’ями.

Регулярные выражения могут содержать выделения (0.7.40), которые могут
затем использоваться в других директивах.

Если у совпавшего префиксного location’а максимальной длины указан модификатор
^~”, то регулярные выражения не проверяются.

Кроме того, с помощью модификатора “=” можно задать точное
совпадение URI и location.
При точном совпадении поиск сразу же прекращается.
Например, если запрос “/” случается часто, то
указав “location = /”, можно ускорить обработку
этих запросов, так как поиск прекратится после первого же сравнения.
Очевидно, что такой location не может иметь вложенные location’ы.

В версиях с 0.7.1 по 0.8.41, если запрос точно совпал с префиксным
location’ом без модификаторов “=” и “^~”,
то поиск тоже сразу же прекращается и регулярные выражения также
не проверяются.

Проиллюстрируем вышесказанное примером:

location = / {
    [ конфигурация А ]
}

location / {
    [ конфигурация Б ]
}

location /documents/ {
    [ конфигурация В ]
}

location ^~ /images/ {
    [ конфигурация Г ]
}

location ~* .(gif|jpg|jpeg)$ {
    [ конфигурация Д ]
}

Для запроса “/” будет выбрана конфигурация А,
для запроса “/index.html” — конфигурация Б,
для запроса “/documents/document.html” — конфигурация В,
для запроса “/images/1.gif” — конфигурация Г,
а для запроса “/documents/1.jpg” — конфигурация Д.

Префикс “@” задаёт именованный location.
Такой location не используется при обычной обработке запросов, а
предназначен только для перенаправления в него запросов.
Такие location’ы не могут быть вложенными и не могут содержать
вложенные location’ы.

Если location задан префиксной строкой со слэшом в конце
и запросы обрабатываются при помощи
proxy_pass,
fastcgi_pass,
uwsgi_pass,
scgi_pass,
memcached_pass или
grpc_pass,
происходит специальная обработка.
В ответ на запрос с URI равным этой строке, но без завершающего слэша,
будет возвращено постоянное перенаправление с кодом 301
на URI с добавленным в конец слэшом.
Если такое поведение нежелательно, можно задать точное совпадение
URI и location, например:

location /user/ {
    proxy_pass http://user.example.com;
}

location = /user {
    proxy_pass http://login.example.com;
}
Синтаксис: log_not_found on | off;
Умолчание:
log_not_found on;
Контекст: http, server, location

Разрешает или запрещает записывать в
error_log
ошибки о том, что файл не найден.

Синтаксис: log_subrequest on | off;
Умолчание:
log_subrequest off;
Контекст: http, server, location

Разрешает или запрещает записывать в
access_log
подзапросы.

Синтаксис: max_ranges число;
Умолчание:

Контекст: http, server, location

Эта директива появилась в версии 1.1.2.

Ограничивает максимальное допустимое число диапазонов в запросах с
указанием диапазона запрашиваемых байт (byte-range requests).
Запросы, превышающие указанное ограничение, обрабатываются как
если бы они не содержали указания диапазонов.
По умолчанию число диапазонов не ограничено.
Значение 0 полностью запрещает поддержку диапазонов.

Синтаксис: merge_slashes on | off;
Умолчание:
merge_slashes on;
Контекст: http, server

Разрешает или запрещает преобразование URI путём замены двух и более подряд
идущих слэшей (“/”) на один.

Необходимо иметь в виду, что это преобразование необходимо для корректной
проверки префиксных строк и регулярных выражений.
Если его не делать, то запрос “//scripts/one.php
не попадёт в

location /scripts/ {
    ...
}

и может быть обслужен как статический файл.
Поэтому он преобразуется к виду “/scripts/one.php”.

Запрет преобразования может понадобиться, если в URI используются имена,
закодированные методом base64, в котором задействован символ
/”.
Однако из соображений безопасности лучше избегать отключения преобразования.

Если директива указана на уровне server,
то может использоваться значение из сервера по умолчанию.
Подробнее см. в разделе
“Выбор
виртуального сервера”.

Синтаксис: msie_padding on | off;
Умолчание:
msie_padding on;
Контекст: http, server, location

Разрешает или запрещает добавлять в ответы для MSIE со статусом больше 400
комментарий для увеличения размера ответа до 512 байт.

Синтаксис: msie_refresh on | off;
Умолчание:
msie_refresh off;
Контекст: http, server, location

Разрешает или запрещает выдавать для MSIE клиентов refresh’ы вместо
перенаправлений.

Синтаксис: open_file_cache off;
open_file_cache
max=N
[inactive=время];
Умолчание:
open_file_cache off;
Контекст: http, server, location

Задаёт кэш, в котором могут храниться:

  • дескрипторы открытых файлов, информация об их размерах и времени модификации;
  • информация о существовании каталогов;
  • информация об ошибках поиска файла — “нет файла”, “нет прав на чтение”
    и тому подобное.

    Кэширование ошибок нужно разрешить отдельно директивой
    open_file_cache_errors.

У директивы есть следующие параметры:

max
задаёт максимальное число элементов в кэше;
при переполнении кэша удаляются наименее востребованные элементы (LRU);
inactive
задаёт время, после которого элемент кэша удаляется, если к нему
не было обращений в течение этого времени; по умолчанию 60 секунд;
off
запрещает кэш.

Пример:

open_file_cache          max=1000 inactive=20s;
open_file_cache_valid    30s;
open_file_cache_min_uses 2;
open_file_cache_errors   on;

Синтаксис: open_file_cache_errors on | off;
Умолчание:
open_file_cache_errors off;
Контекст: http, server, location

Разрешает или запрещает кэширование ошибок поиска файлов в
open_file_cache.

Синтаксис: open_file_cache_min_uses число;
Умолчание:
open_file_cache_min_uses 1;
Контекст: http, server, location

Задаёт минимальное число обращений к файлу
в течение времени, заданного параметром inactive
директивы open_file_cache, необходимых для того, чтобы дескриптор
файла оставался открытым в кэше.

Синтаксис: open_file_cache_valid время;
Умолчание:
open_file_cache_valid 60s;
Контекст: http, server, location

Определяет время, через которое следует проверять актуальность информации
об элементе в
open_file_cache.

Синтаксис: output_buffers number size;
Умолчание:
output_buffers 2 32k;
Контекст: http, server, location

Задаёт число и размер буферов,
используемых при чтении ответа с диска.

До версии 1.9.5 по умолчанию использовалось значение 1 32k.

Синтаксис: port_in_redirect on | off;
Умолчание:
port_in_redirect on;
Контекст: http, server, location

Разрешает или запрещает указывать порт в
абсолютных
перенаправлениях, выдаваемых nginx’ом.

Использование в перенаправлениях основного имени сервера управляется
директивой server_name_in_redirect.

Синтаксис: postpone_output размер;
Умолчание:
postpone_output 1460;
Контекст: http, server, location

Если это возможно, то отправка данных клиенту будет отложена пока nginx не
накопит по крайней мере указанное количество байт для отправки.
Значение 0 запрещает отложенную отправку данных.

Синтаксис: read_ahead размер;
Умолчание:
read_ahead 0;
Контекст: http, server, location

Задаёт ядру размер предчтения при работе с файлами.

На Linux используется системный вызов
posix_fadvise(0, 0, 0, POSIX_FADV_SEQUENTIAL),
поэтому параметр размер там игнорируется.

На FreeBSD используется системный вызов
fcntl(O_READAHEAD,
размер),
появившийся во FreeBSD 9.0-CURRENT.
Для FreeBSD 7 необходимо установить
патч.

Синтаксис: recursive_error_pages on | off;
Умолчание:
recursive_error_pages off;
Контекст: http, server, location

Разрешает или запрещает делать несколько перенаправлений через директиву
error_page.
Число таких перенаправлений ограничено.

Синтаксис: request_pool_size размер;
Умолчание:
request_pool_size 4k;
Контекст: http, server

Позволяет производить точную настройку выделений памяти
под конкретные запросы.
Эта директива не оказывает существенного влияния на
производительность, и её не следует использовать.

Синтаксис: reset_timedout_connection on | off;
Умолчание:
reset_timedout_connection off;
Контекст: http, server, location

Разрешает или запрещает сброс соединений по таймауту,
а также при
закрытии
соединений с помощью нестандартного кода 444 (1.15.2).
Сброс делается следующим образом.
Перед закрытием сокета для него задаётся параметр
SO_LINGER
с таймаутом 0.
После этого при закрытии сокета клиенту отсылается TCP RST, а вся память,
связанная с этим сокетом, освобождается.
Это позволяет избежать длительного нахождения уже закрытого сокета в
состоянии FIN_WAIT1 с заполненными буферами.

Необходимо отметить, что keep-alive соединения по истечении таймаута
закрываются обычным образом.

Синтаксис: resolver
адрес ...
[valid=время]
[ipv4=on|off]
[ipv6=on|off]
[status_zone=зона];
Умолчание:

Контекст: http, server, location

Задаёт серверы DNS, используемые для преобразования имён вышестоящих серверов
в адреса, например:

resolver 127.0.0.1 [::1]:5353;

Адрес может быть указан в виде доменного имени или IP-адреса,
и необязательного порта (1.3.1, 1.2.2).
Если порт не указан, используется порт 53.
Серверы DNS опрашиваются циклически.

До версии 1.1.7 можно было задать лишь один DNS-сервер.
Задание DNS-серверов с помощью IPv6-адресов поддерживается
начиная с версий 1.3.1 и 1.2.2.

По умолчанию nginx будет искать как IPv4-, так и IPv6-адреса
при преобразовании имён в адреса.
Если поиск IPv4- или IPv6-адресов нежелателен,
можно указать параметр ipv4=off (1.23.1) или
ipv6=off.

Преобразование имён в IPv6-адреса поддерживается
начиная с версии 1.5.8.

По умолчанию nginx кэширует ответы, используя значение TTL из ответа.
Необязательный параметр valid позволяет это
переопределить:

resolver 127.0.0.1 [::1]:5353 valid=30s;

До версии 1.1.9 настройка времени кэширования была невозможна
и nginx всегда кэшировал ответы на срок в 5 минут.

Для предотвращения DNS-спуфинга рекомендуется
использовать DNS-серверы в защищённой доверенной локальной сети.

Необязательный параметр status_zone (1.17.1)
включает
сбор информации
о запросах и ответах сервера DNS
в указанной зоне.
Параметр доступен как часть
коммерческой подписки.

Синтаксис: resolver_timeout время;
Умолчание:
resolver_timeout 30s;
Контекст: http, server, location

Задаёт таймаут для преобразования имени в адрес, например:

resolver_timeout 5s;
Синтаксис: root путь;
Умолчание:
root html;
Контекст: http, server, location, if в location

Задаёт корневой каталог для запросов.
Например, при такой конфигурации

location /i/ {
    root /data/w3;
}

в ответ на запрос “/i/top.gif” будет отдан файл
/data/w3/i/top.gif.

В значении параметра путь можно использовать переменные,
кроме $document_root и $realpath_root.

Путь к файлу формируется путём простого добавления URI к значению директивы
root.
Если же URI необходимо поменять, следует воспользоваться директивой
alias.

Синтаксис: satisfy all | any;
Умолчание:
satisfy all;
Контекст: http, server, location

Разрешает доступ, если все (all)
или хотя бы один (any) из модулей
ngx_http_access_module,
ngx_http_auth_basic_module,
ngx_http_auth_request_module
или
ngx_http_auth_jwt_module
разрешают доступ.

Пример:

location / {
    satisfy any;

    allow 192.168.1.0/32;
    deny  all;

    auth_basic           "closed site";
    auth_basic_user_file conf/htpasswd;
}
Синтаксис: send_lowat размер;
Умолчание:
send_lowat 0;
Контекст: http, server, location

При установке этой директивы в ненулевое значение nginx будет пытаться
минимизировать число операций отправки на клиентских сокетах либо при
помощи флага NOTE_LOWAT метода
kqueue,
либо при помощи параметра сокета SO_SNDLOWAT.
В обоих случаях будет использован указанный размер.

Эта директива игнорируется на Linux, Solaris и Windows.

Синтаксис: send_timeout время;
Умолчание:
send_timeout 60s;
Контекст: http, server, location

Задаёт таймаут при передаче ответа клиенту.
Таймаут устанавливается не на всю передачу ответа,
а только между двумя операциями записями.
Если по истечении этого времени клиент ничего не примет,
соединение будет закрыто.

Синтаксис: sendfile on | off;
Умолчание:
sendfile off;
Контекст: http, server, location, if в location

Разрешает или запрещает использовать
sendfile().

Начиная с nginx 0.8.12 и FreeBSD 5.2.1,
можно использовать aio для подгрузки данных
для sendfile():

location /video/ {
    sendfile       on;
    tcp_nopush     on;
    aio            on;
}

В такой конфигурации функция sendfile() вызывается с флагом
SF_NODISKIO, в результате чего она не блокируется на диске, а
сообщает об отсутствии данных в памяти.
После этого nginx инициирует асинхронную подгрузку данных, читая один байт.
При этом ядро FreeBSD подгружает в память первые 128K байт файла, однако
при последующих чтениях файл подгружается частями только по 16K.
Изменить это можно с помощью директивы
read_ahead.

До версии 1.7.11 подгрузка данных включалась с помощью
aio sendfile;.

Синтаксис: sendfile_max_chunk размер;
Умолчание:
sendfile_max_chunk 2m;
Контекст: http, server, location

Ограничивает объём данных,
который может передан за один вызов sendfile().
Без этого ограничения одно быстрое соединение может целиком
захватить рабочий процесс.

До версии 1.21.4 по умолчанию ограничения не было.

Синтаксис: server { ... }
Умолчание:

Контекст: http

Задаёт конфигурацию для виртуального сервера.
Чёткого разделения виртуальных серверов на IP-based (на основании IP-адреса)
и name-based (на основании поля “Host” заголовка запроса) нет.
Вместо этого директивами listen описываются все
адреса и порты, на которых нужно принимать соединения для этого сервера,
а в директиве server_name указываются все имена серверов.
Примеры конфигураций описаны в документе
“Как nginx обрабатывает запросы”.

Синтаксис: server_name имя ...;
Умолчание:
server_name "";
Контекст: server

Задаёт имена виртуального сервера, например:

server {
    server_name example.com www.example.com;
}

Первое имя становится основным именем сервера.

В именах серверов можно использовать звёздочку (“*”)
для замены первой или последней части имени:

server {
    server_name example.com *.example.com www.example.*;
}

Такие имена называются именами с маской.

Два первых вышеприведённых имени можно объединить в одно:

server {
    server_name .example.com;
}

В качестве имени сервера можно также использовать регулярное выражение,
указав перед ним тильду (“~”):

server {
    server_name www.example.com ~^wwwd+.example.com$;
}

Регулярное выражение может содержать выделения (0.7.40),
которые могут затем использоваться в других директивах:

server {
    server_name ~^(www.)?(.+)$;

    location / {
        root /sites/$2;
    }
}

server {
    server_name _;

    location / {
        root /sites/default;
    }
}

Именованные выделения в регулярном выражении создают переменные (0.8.25),
которые могут затем использоваться в других директивах:

server {
    server_name ~^(www.)?(?<domain>.+)$;

    location / {
        root /sites/$domain;
    }
}

server {
    server_name _;

    location / {
        root /sites/default;
    }
}

Если параметр директивы установлен в “$hostname” (0.9.4), то
подставляется имя хоста (hostname) машины.

Возможно также указать пустое имя сервера (0.7.11):

server {
    server_name www.example.com "";
}

Это позволяет обрабатывать запросы без поля “Host” заголовка
запроса в этом сервере, а не в сервере по умолчанию для данной пары адрес:порт.
Это настройка по умолчанию.

До 0.8.48 по умолчанию использовалось имя хоста (hostname) машины.

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

  1. точное имя
  2. самое длинное имя с маской в начале,
    например “*.example.com
  3. самое длинное имя с маской в конце,
    например “mail.*
  4. первое подходящее регулярное выражение
    (в порядке следования в конфигурационном файле)

Подробнее имена серверов обсуждаются в отдельном
документе.

Синтаксис: server_name_in_redirect on | off;
Умолчание:
server_name_in_redirect off;
Контекст: http, server, location

Разрешает или запрещает использовать в
абсолютных перенаправлениях,
выдаваемых nginx’ом, основное имя сервера, задаваемое директивой
server_name.
Если использование основного имени сервера запрещено, то используется имя,
указанное в поле “Host” заголовка запроса.
Если же этого поля нет, то используется IP-адрес сервера.

Использование в перенаправлениях порта управляется
директивой port_in_redirect.

Синтаксис: server_names_hash_bucket_size размер;
Умолчание:
server_names_hash_bucket_size 32|64|128;
Контекст: http

Задаёт размер корзины в хэш-таблицах имён серверов.
Значение по умолчанию зависит от размера строки кэша процессора.
Подробнее настройка хэш-таблиц обсуждается в отдельном
документе.

Синтаксис: server_names_hash_max_size размер;
Умолчание:
server_names_hash_max_size 512;
Контекст: http

Задаёт максимальный размер хэш-таблиц имён серверов.
Подробнее настройка хэш-таблиц обсуждается в отдельном
документе.

Синтаксис: server_tokens
on |
off |
build |
строка;
Умолчание:
server_tokens on;
Контекст: http, server, location

Разрешает или запрещает выдавать версию nginx’а на страницах ошибок и
в поле “Server” заголовка ответа.

Если указан параметр build (1.11.10),
то наряду с версией nginx’а будет также выдаваться
имя сборки.

Дополнительно, как часть
коммерческой подписки,
начиная с версии 1.9.13
подписи на страницах ошибок и
значение поля “Server” заголовка ответа
можно задать явно с помощью строки с переменными.
Пустая строка запрещает выдачу поля “Server”.

Синтаксис: subrequest_output_buffer_size размер;
Умолчание:
subrequest_output_buffer_size 4k|8k;
Контекст: http, server, location

Эта директива появилась в версии 1.13.10.

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

Директива применима только для подзапросов,
тело ответа которых сохраняется в памяти.
Например, подобные подзапросы создаются при помощи
SSI.

Синтаксис: tcp_nodelay on | off;
Умолчание:
tcp_nodelay on;
Контекст: http, server, location

Разрешает или запрещает использование параметра TCP_NODELAY.
Параметр включается при переходе соединения в состояние keep-alive.
Также, он включается на SSL-соединениях,
при небуферизованном проксировании
и при проксировании WebSocket.

Синтаксис: tcp_nopush on | off;
Умолчание:
tcp_nopush off;
Контекст: http, server, location

Разрешает или запрещает использование параметра сокета
TCP_NOPUSH во FreeBSD или
TCP_CORK в Linux.
Параметр включаются только при использовании sendfile.
Включение параметра позволяет

  • передавать заголовок ответа и начало файла в одном пакете
    в Linux и во FreeBSD 4.*;
  • передавать файл полными пакетами.
Синтаксис: try_files файл ... uri;
try_files файл ... =код;
Умолчание:

Контекст: server, location

Проверяет существование файлов в заданном порядке и использует
для обработки запроса первый найденный файл, причём обработка
делается в контексте этого же location’а.
Путь к файлу строится из параметра файл
в соответствии с директивами
root и alias.
С помощью слэша в конце имени можно проверить существование каталога,
например, “$uri/”.
В случае, если ни один файл не найден, то делается внутреннее
перенаправление на uri, заданный последним параметром.
Например:

location /images/ {
    try_files $uri /images/default.gif;
}

location = /images/default.gif {
    expires 30s;
}

Последний параметр может также указывать на именованный location,
как в примерах ниже.
С версии 0.7.51 последний параметр может также быть кодом:

location / {
    try_files $uri $uri/index.html $uri.html =404;
}

Пример использования при проксировании Mongrel:

location / {
    try_files /system/maintenance.html
              $uri $uri/index.html $uri.html
              @mongrel;
}

location @mongrel {
    proxy_pass http://mongrel;
}

Пример использования вместе с Drupal/FastCGI:

location / {
    try_files $uri $uri/ @drupal;
}

location ~ .php$ {
    try_files $uri @drupal;

    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;
    fastcgi_param SCRIPT_NAME     $fastcgi_script_name;
    fastcgi_param QUERY_STRING    $args;

    ... прочие fastcgi_param
}

location @drupal {
    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to/index.php;
    fastcgi_param SCRIPT_NAME     /index.php;
    fastcgi_param QUERY_STRING    q=$uri&$args;

    ... прочие fastcgi_param
}

В следующем примере директива try_files

location / {
    try_files $uri $uri/ @drupal;
}

аналогична директивам

location / {
    error_page 404 = @drupal;
    log_not_found off;
}

А здесь

location ~ .php$ {
    try_files $uri @drupal;

    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;

    ...
}

try_files проверяет существование PHP-файла,
прежде чем передать запрос FastCGI-серверу.

Пример использования вместе с WordPress и Joomla:

location / {
    try_files $uri $uri/ @wordpress;
}

location ~ .php$ {
    try_files $uri @wordpress;

    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;
    ... прочие fastcgi_param
}

location @wordpress {
    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to/index.php;
    ... прочие fastcgi_param
}
Синтаксис: types { ... }
Умолчание:
types {
    text/html  html;
    image/gif  gif;
    image/jpeg jpg;
}
Контекст: http, server, location

Задаёт соответствие расширений имён файлов и MIME-типов ответов.
Расширения нечувствительны к регистру символов.
Одному MIME-типу может соответствовать несколько расширений, например:

types {
    application/octet-stream bin exe dll;
    application/octet-stream deb;
    application/octet-stream dmg;
}

Достаточно полная таблица соответствий входит в дистрибутив nginx
и находится в файле conf/mime.types.

Для того чтобы для определённого location’а для всех ответов
выдавался MIME-тип “application/octet-stream”,
можно использовать следующее:

location /download/ {
    types        { }
    default_type application/octet-stream;
}
Синтаксис: types_hash_bucket_size размер;
Умолчание:
types_hash_bucket_size 64;
Контекст: http, server, location

Задаёт размер корзины в хэш-таблицах типов.
Подробнее настройка хэш-таблиц обсуждается в отдельном
документе.

До версии 1.5.13
значение по умолчанию зависело от размера строки кэша процессора.

Синтаксис: types_hash_max_size размер;
Умолчание:
types_hash_max_size 1024;
Контекст: http, server, location

Задаёт максимальный размер хэш-таблиц типов.
Подробнее настройка хэш-таблиц обсуждается в отдельном
документе.

Синтаксис: underscores_in_headers on | off;
Умолчание:
underscores_in_headers off;
Контекст: http, server

Разрешает или запрещает использование символов подчёркивания в
полях заголовка запроса клиента.
Если использование символов подчёркивания запрещено, поля заголовка запроса, в
именах которых есть подчёркивания,
помечаются как недопустимые и подпадают под действие директивы
ignore_invalid_headers.

Если директива указана на уровне server,
то может использоваться значение из сервера по умолчанию.
Подробнее см. в разделе
“Выбор
виртуального сервера”.

Синтаксис: variables_hash_bucket_size размер;
Умолчание:
variables_hash_bucket_size 64;
Контекст: http

Задаёт размер корзины в хэш-таблице переменных.
Подробнее настройка хэш-таблиц обсуждается в отдельном
документе.

Синтаксис: variables_hash_max_size размер;
Умолчание:
variables_hash_max_size 1024;
Контекст: http

Задаёт максимальный размер хэш-таблицы переменных.
Подробнее настройка хэш-таблиц обсуждается в отдельном
документе.

До версии 1.5.13 по умолчанию использовалось значение 512.

Встроенные переменные

Модуль ngx_http_core_module поддерживает встроенные
переменные, имена которых совпадают с именами переменных веб-сервера Apache.
Прежде всего, это переменные, представляющие из себя поля заголовка
запроса клиента, такие как $http_user_agent, $http_cookie
и тому подобное.
Кроме того, есть и другие переменные:

$arg_имя
аргумент имя в строке запроса
$args
аргументы в строке запроса
$binary_remote_addr
адрес клиента в бинарном виде, длина значения всегда 4 байта
для IPv4-адресов или 16 байт для IPv6-адресов
$body_bytes_sent
число байт, переданное клиенту, без учёта заголовка ответа;
переменная совместима с параметром “%B” модуля Apache
mod_log_config
$bytes_sent
число байт, переданных клиенту (1.3.8, 1.2.5)
$connection
порядковый номер соединения (1.3.8, 1.2.5)
$connection_requests
текущее число запросов в соединении (1.3.8, 1.2.5)
$connection_time
время соединения в секундах с точностью до миллисекунд (1.19.10)
$content_length
поле “Content-Length” заголовка запроса
$content_type
поле “Content-Type” заголовка запроса
$cookie_имя
cookie имя
$document_root
значение директивы root или alias
для текущего запроса
$document_uri
то же, что и $uri
$host
в порядке приоритета:
имя хоста из строки запроса, или
имя хоста из поля “Host” заголовка запроса, или
имя сервера, соответствующего запросу
$hostname
имя хоста
$http_имя
произвольное поле заголовка запроса;
последняя часть имени переменной соответствует имени поля, приведённому
к нижнему регистру, с заменой символов тире на символы подчёркивания
$https
on
если соединение работает в режиме SSL,
либо пустая строка
$is_args
?”, если в строке запроса есть аргументы,
и пустая строка, если их нет
$limit_rate
установка этой переменной позволяет ограничивать скорость
передачи ответа, см. limit_rate
$msec
текущее время в секундах с точностью до миллисекунд (1.3.9, 1.2.6)
$nginx_version
версия nginx
$pid
номер (PID) рабочего процесса
$pipe
p” если запрос был pipelined, иначе “.
(1.3.12, 1.2.7)
$proxy_protocol_addr
адрес клиента, полученный из заголовка протокола PROXY (1.5.12)

Протокол PROXY должен быть предварительно включён при помощи установки
параметра proxy_protocol в директиве listen.

$proxy_protocol_port
порт клиента, полученный из заголовка протокола PROXY (1.11.0)

Протокол PROXY должен быть предварительно включён при помощи установки
параметра proxy_protocol в директиве listen.

$proxy_protocol_server_addr
адрес сервера, полученный из заголовка протокола PROXY (1.17.6)

Протокол PROXY должен быть предварительно включён при помощи установки
параметра proxy_protocol в директиве listen.

$proxy_protocol_server_port
порт сервера, полученный из заголовка протокола PROXY (1.17.6)

Протокол PROXY должен быть предварительно включён при помощи установки
параметра proxy_protocol в директиве listen.

$proxy_protocol_tlv_имя
TLV, полученный из заголовка протокола PROXY (1.23.2).
Имя может быть именем типа TLV или его числовым значением.
В последнем случае значение задаётся в шестнадцатеричном виде
и должно начинаться с 0x:

$proxy_protocol_tlv_alpn
$proxy_protocol_tlv_0x01

SSL TLV могут также быть доступны как по имени типа TLV,
так и по его числовому значению,
оба должны начинаться с ssl_:

$proxy_protocol_tlv_ssl_version
$proxy_protocol_tlv_ssl_0x21

Поддерживаются следующие имена типов TLV:

  • alpn (0x01) —
    протокол более высокого уровня, используемый поверх соединения
  • authority (0x02) —
    значение имени хоста, передаваемое клиентом
  • unique_id (0x05) —
    уникальный идентификатор соединения
  • netns (0x30) —
    имя пространства имён
  • ssl (0x20) —
    структура SSL TLV в бинарном виде

Поддерживаются следующие имена типов SSL TLV:

  • ssl_version (0x21) —
    версия SSL, используемая в клиентском соединении
  • ssl_cn (0x22) —
    Common Name сертификата
  • ssl_cipher (0x23) —
    имя используемого шифра
  • ssl_sig_alg (0x24) —
    алгоритм, используемый для подписи сертификата
  • ssl_key_alg (0x25) —
    алгоритм публичного ключа

Также поддерживается следующее специальное имя типа SSL TLV:

  • ssl_verify —
    результат проверки клиентского сертификата:
    0, если клиент предоставил сертификат
    и он был успешно верифицирован,
    либо ненулевое значение

Протокол PROXY должен быть предварительно включён при помощи установки
параметра proxy_protocol в директиве listen.

$query_string
то же, что и $args
$realpath_root
абсолютный путь, соответствующий
значению директивы root или alias
для текущего запроса,
в котором все символические ссылки преобразованы в реальные пути
$remote_addr
адрес клиента
$remote_port
порт клиента
$remote_user
имя пользователя, использованное в Basic аутентификации
$request
первоначальная строка запроса целиком
$request_body
тело запроса

Значение переменной появляется в location’ах, обрабатываемых
директивами
proxy_pass,
fastcgi_pass,
uwsgi_pass
и
scgi_pass,
когда тело было прочитано в
буфер в памяти.

$request_body_file
имя временного файла, в котором хранится тело запроса

По завершении обработки файл необходимо удалить.
Для того чтобы тело запроса всегда записывалось в файл,
следует включить client_body_in_file_only.
При передаче имени временного файла в проксированном запросе
или в запросе к FastCGI/uwsgi/SCGI-серверу следует запретить передачу самого
тела директивами

proxy_pass_request_body off,

fastcgi_pass_request_body off,

uwsgi_pass_request_body off
или

scgi_pass_request_body off
соответственно.

$request_completion
OK” если запрос завершился,
либо пустая строка
$request_filename
путь к файлу для текущего запроса, формируемый из директив
root или alias и URI запроса
$request_id
уникальный идентификатор запроса,
сформированный из 16 случайных байт, в шестнадцатеричном виде (1.11.0)
$request_length
длина запроса (включая строку запроса, заголовок и тело запроса)
(1.3.12, 1.2.7)
$request_method
метод запроса, обычно
GET” или “POST
$request_time
время обработки запроса в секундах с точностью до миллисекунд
(1.3.9, 1.2.6);
время, прошедшее с момента чтения первых байт от клиента
$request_uri
первоначальный URI запроса целиком (с аргументами)
$scheme
схема запроса, “http” или “https
$sent_http_имя
произвольное поле заголовка ответа;
последняя часть имени переменной соответствует имени поля, приведённому
к нижнему регистру, с заменой символов тире на символы подчёркивания
$sent_trailer_имя
произвольное поле, отправленное в конце ответа (1.13.2);
последняя часть имени переменной соответствует имени поля, приведённому
к нижнему регистру, с заменой символов тире на символы подчёркивания
$server_addr
адрес сервера, принявшего запрос

Получение значения этой переменной обычно требует одного системного вызова.
Чтобы избежать системного вызова, в директивах listen
следует указывать адреса и использовать параметр bind.

$server_name
имя сервера, принявшего запрос
$server_port
порт сервера, принявшего запрос
$server_protocol
протокол запроса, обычно
HTTP/1.0”,
HTTP/1.1
или
“HTTP/2.0”
$status
статус ответа (1.3.2, 1.2.2)
$time_iso8601
локальное время в формате по стандарту ISO 8601 (1.3.12, 1.2.7)
$time_local
локальное время в Common Log Format (1.3.12, 1.2.7)
$tcpinfo_rtt,
$tcpinfo_rttvar,
$tcpinfo_snd_cwnd,
$tcpinfo_rcv_space
информация о клиентском TCP-соединении; доступна на системах,
поддерживающих параметр сокета TCP_INFO
$uri
текущий URI запроса в нормализованном виде

Значение $uri может изменяться в процессе обработки запроса,
например, при внутренних перенаправлениях
или при использовании индексных файлов.

Directives

Syntax: absolute_redirect on | off;
Default:
absolute_redirect on;
Context: http, server, location

This directive appeared in version 1.11.8.

If disabled, redirects issued by nginx will be relative.

See also server_name_in_redirect
and port_in_redirect directives.

Syntax: aio
on |
off |
threads[=pool];
Default:
aio off;
Context: http, server, location

This directive appeared in version 0.8.11.

Enables or disables the use of asynchronous file I/O (AIO)
on FreeBSD and Linux:

location /video/ {
    aio            on;
    output_buffers 1 64k;
}

On FreeBSD, AIO can be used starting from FreeBSD 4.3.
Prior to FreeBSD 11.0,
AIO can either be linked statically into a kernel:

options VFS_AIO

or loaded dynamically as a kernel loadable module:

kldload aio

On Linux, AIO can be used starting from kernel version 2.6.22.
Also, it is necessary to enable
directio,
or otherwise reading will be blocking:

location /video/ {
    aio            on;
    directio       512;
    output_buffers 1 128k;
}

On Linux,
directio
can only be used for reading blocks that are aligned on 512-byte
boundaries (or 4K for XFS).
File’s unaligned end is read in blocking mode.
The same holds true for byte range requests and for FLV requests
not from the beginning of a file: reading of unaligned data at the
beginning and end of a file will be blocking.

When both AIO and sendfile are enabled on Linux,
AIO is used for files that are larger than or equal to
the size specified in the directio directive,
while sendfile is used for files of smaller sizes
or when directio is disabled.

location /video/ {
    sendfile       on;
    aio            on;
    directio       8m;
}

Finally, files can be read and sent
using multi-threading (1.7.11),
without blocking a worker process:

location /video/ {
    sendfile       on;
    aio            threads;
}

Read and send file operations are offloaded to threads of the specified
pool.
If the pool name is omitted,
the pool with the name “default” is used.
The pool name can also be set with variables:

aio threads=pool$disk;

By default, multi-threading is disabled, it should be
enabled with the
--with-threads configuration parameter.
Currently, multi-threading is compatible only with the
epoll,
kqueue,
and
eventport methods.
Multi-threaded sending of files is only supported on Linux.

See also the sendfile directive.

Syntax: aio_write on | off;
Default:
aio_write off;
Context: http, server, location

This directive appeared in version 1.9.13.

If aio is enabled, specifies whether it is used for writing files.
Currently, this only works when using
aio threads
and is limited to writing temporary files
with data received from proxied servers.

Syntax: alias path;
Default:

Context: location

Defines a replacement for the specified location.
For example, with the following configuration

location /i/ {
    alias /data/w3/images/;
}

on request of
/i/top.gif”, the file
/data/w3/images/top.gif will be sent.

The path value can contain variables,
except $document_root and $realpath_root.

If alias is used inside a location defined
with a regular expression then such regular expression should
contain captures and alias should refer to
these captures (0.7.40), for example:

location ~ ^/users/(.+.(?:gif|jpe?g|png))$ {
    alias /data/w3/images/$1;
}

When location matches the last part of the directive’s value:

location /images/ {
    alias /data/w3/images/;
}

it is better to use the
root
directive instead:

location /images/ {
    root /data/w3;
}
Syntax: auth_delay time;
Default:
auth_delay 0s;
Context: http, server, location

This directive appeared in version 1.17.10.

Delays processing of unauthorized requests with 401 response code
to prevent timing attacks when access is limited by
password, by the
result of subrequest,
or by JWT.

Syntax: chunked_transfer_encoding on | off;
Default:
chunked_transfer_encoding on;
Context: http, server, location

Allows disabling chunked transfer encoding in HTTP/1.1.
It may come in handy when using a software failing to support
chunked encoding despite the standard’s requirement.

Syntax: client_body_buffer_size size;
Default:
client_body_buffer_size 8k|16k;
Context: http, server, location

Sets buffer size for reading client request body.
In case the request body is larger than the buffer,
the whole body or only its part is written to a
temporary file.
By default, buffer size is equal to two memory pages.
This is 8K on x86, other 32-bit platforms, and x86-64.
It is usually 16K on other 64-bit platforms.

Syntax: client_body_in_file_only
on |
clean |
off;
Default:
client_body_in_file_only off;
Context: http, server, location

Determines whether nginx should save the entire client request body
into a file.
This directive can be used during debugging, or when using the
$request_body_file
variable, or the
$r->request_body_file
method of the module
ngx_http_perl_module.

When set to the value on, temporary files are not
removed after request processing.

The value clean will cause the temporary files
left after request processing to be removed.

Syntax: client_body_in_single_buffer on | off;
Default:
client_body_in_single_buffer off;
Context: http, server, location

Determines whether nginx should save the entire client request body
in a single buffer.
The directive is recommended when using the
$request_body
variable, to save the number of copy operations involved.

Syntax: client_body_temp_path
path
[level1
[level2
[level3]]];
Default:
client_body_temp_path client_body_temp;
Context: http, server, location

Defines a directory for storing temporary files holding client request bodies.
Up to three-level subdirectory hierarchy can be used under the specified
directory.
For example, in the following configuration

client_body_temp_path /spool/nginx/client_temp 1 2;

a path to a temporary file might look like this:

/spool/nginx/client_temp/7/45/00000123457
Syntax: client_body_timeout time;
Default:
client_body_timeout 60s;
Context: http, server, location

Defines a timeout for reading client request body.
The timeout is set only for a period between two successive read operations,
not for the transmission of the whole request body.
If a client does not transmit anything within this time, the
request is terminated with the
408 (Request Time-out)
error.

Syntax: client_header_buffer_size size;
Default:
client_header_buffer_size 1k;
Context: http, server

Sets buffer size for reading client request header.
For most requests, a buffer of 1K bytes is enough.
However, if a request includes long cookies, or comes from a WAP client,
it may not fit into 1K.
If a request line or a request header field does not fit into
this buffer then larger buffers, configured by the
large_client_header_buffers directive,
are allocated.

If the directive is specified on the server level,
the value from the default server can be used.
Details are provided in the
“Virtual
server selection” section.

Syntax: client_header_timeout time;
Default:
client_header_timeout 60s;
Context: http, server

Defines a timeout for reading client request header.
If a client does not transmit the entire header within this time, the
request is terminated with the
408 (Request Time-out)
error.

Syntax: client_max_body_size size;
Default:
client_max_body_size 1m;
Context: http, server, location

Sets the maximum allowed size of the client request body.
If the size in a request exceeds the configured value, the
413 (Request Entity Too Large)
error is returned to the client.
Please be aware that
browsers cannot correctly display
this error.
Setting size to 0 disables checking of client
request body size.

Syntax: connection_pool_size size;
Default:
connection_pool_size 256|512;
Context: http, server

Allows accurate tuning of per-connection memory allocations.
This directive has minimal impact on performance
and should not generally be used.
By default, the size is equal to
256 bytes on 32-bit platforms and 512 bytes on 64-bit platforms.

Prior to version 1.9.8, the default value was 256 on all platforms.

Syntax: default_type mime-type;
Default:
default_type text/plain;
Context: http, server, location

Defines the default MIME type of a response.
Mapping of file name extensions to MIME types can be set
with the types directive.

Syntax: directio size | off;
Default:
directio off;
Context: http, server, location

This directive appeared in version 0.7.7.

Enables the use of
the O_DIRECT flag (FreeBSD, Linux),
the F_NOCACHE flag (macOS),
or the directio() function (Solaris),
when reading files that are larger than or equal to
the specified size.
The directive automatically disables (0.7.15) the use of
sendfile
for a given request.
It can be useful for serving large files:

directio 4m;

or when using aio on Linux.

Syntax: directio_alignment size;
Default:
directio_alignment 512;
Context: http, server, location

This directive appeared in version 0.8.11.

Sets the alignment for
directio.
In most cases, a 512-byte alignment is enough.
However, when using XFS under Linux, it needs to be increased to 4K.

Syntax: disable_symlinks off;
disable_symlinks
on |
if_not_owner
[from=part];
Default:
disable_symlinks off;
Context: http, server, location

This directive appeared in version 1.1.15.

Determines how symbolic links should be treated when opening files:

off
Symbolic links in the pathname are allowed and not checked.
This is the default behavior.
on
If any component of the pathname is a symbolic link,
access to a file is denied.
if_not_owner
Access to a file is denied if any component of the pathname
is a symbolic link, and the link and object that the link
points to have different owners.
from=part
When checking symbolic links
(parameters on and if_not_owner),
all components of the pathname are normally checked.
Checking of symbolic links in the initial part of the pathname
may be avoided by specifying additionally the
from=part parameter.
In this case, symbolic links are checked only from
the pathname component that follows the specified initial part.
If the value is not an initial part of the pathname checked, the whole
pathname is checked as if this parameter was not specified at all.
If the value matches the whole file name,
symbolic links are not checked.
The parameter value can contain variables.

Example:

disable_symlinks on from=$document_root;

This directive is only available on systems that have the
openat() and fstatat() interfaces.
Such systems include modern versions of FreeBSD, Linux, and Solaris.

Parameters on and if_not_owner
add a processing overhead.

On systems that do not support opening of directories only for search,
to use these parameters it is required that worker processes
have read permissions for all directories being checked.

The
ngx_http_autoindex_module,
ngx_http_random_index_module,
and ngx_http_dav_module
modules currently ignore this directive.

Syntax: error_page
code ...
[=[response]]
uri;
Default:

Context: http, server, location, if in location

Defines the URI that will be shown for the specified errors.
A uri value can contain variables.

Example:

error_page 404             /404.html;
error_page 500 502 503 504 /50x.html;

This causes an internal redirect to the specified uri
with the client request method changed to “GET
(for all methods other than
GET” and “HEAD”).

Furthermore, it is possible to change the response code to another
using the “=response” syntax, for example:

error_page 404 =200 /empty.gif;

If an error response is processed by a proxied server
or a FastCGI/uwsgi/SCGI/gRPC server,
and the server may return different response codes (e.g., 200, 302, 401
or 404), it is possible to respond with the code it returns:

error_page 404 = /404.php;

If there is no need to change URI and method during internal redirection
it is possible to pass error processing into a named location:

location / {
    error_page 404 = @fallback;
}

location @fallback {
    proxy_pass http://backend;
}

If uri processing leads to an error,
the status code of the last occurred error is returned to the client.

It is also possible to use URL redirects for error processing:

error_page 403      http://example.com/forbidden.html;
error_page 404 =301 http://example.com/notfound.html;

In this case, by default, the response code 302 is returned to the client.
It can only be changed to one of the redirect status
codes (301, 302, 303, 307, and 308).

The code 307 was not treated as a redirect until versions 1.1.16 and 1.0.13.

The code 308 was not treated as a redirect until version 1.13.0.

These directives are inherited from the previous configuration level
if and only if there are no error_page directives
defined on the current level.

Syntax: etag on | off;
Default:
etag on;
Context: http, server, location

This directive appeared in version 1.3.3.

Enables or disables automatic generation of the “ETag”
response header field for static resources.

Syntax: http { ... }
Default:

Context: main

Provides the configuration file context in which the HTTP server directives
are specified.

Syntax: if_modified_since
off |
exact |
before;
Default:
if_modified_since exact;
Context: http, server, location

This directive appeared in version 0.7.24.

Specifies how to compare modification time of a response
with the time in the
“If-Modified-Since”
request header field:

off
the response is always considered modified (0.7.34);
exact
exact match;
before
modification time of the response is
less than or equal to the time in the “If-Modified-Since”
request header field.
Syntax: ignore_invalid_headers on | off;
Default:
ignore_invalid_headers on;
Context: http, server

Controls whether header fields with invalid names should be ignored.
Valid names are composed of English letters, digits, hyphens, and possibly
underscores (as controlled by the underscores_in_headers
directive).

If the directive is specified on the server level,
the value from the default server can be used.
Details are provided in the
“Virtual
server selection” section.

Syntax: internal;
Default:

Context: location

Specifies that a given location can only be used for internal requests.
For external requests, the client error
404 (Not Found)
is returned.
Internal requests are the following:

  • requests redirected by the
    error_page,
    index,
    random_index, and
    try_files directives;
  • requests redirected by the “X-Accel-Redirect”
    response header field from an upstream server;
  • subrequests formed by the
    include virtual
    command of the
    ngx_http_ssi_module
    module, by the
    ngx_http_addition_module
    module directives, and by
    auth_request and
    mirror directives;
  • requests changed by the
    rewrite directive.

Example:

error_page 404 /404.html;

location = /404.html {
    internal;
}

There is a limit of 10 internal redirects per request to prevent
request processing cycles that can occur in incorrect configurations.
If this limit is reached, the error
500 (Internal Server Error) is returned.
In such cases, the “rewrite or internal redirection cycle” message
can be seen in the error log.

Syntax: keepalive_disable none | browser ...;
Default:
keepalive_disable msie6;
Context: http, server, location

Disables keep-alive connections with misbehaving browsers.
The browser parameters specify which
browsers will be affected.
The value msie6 disables keep-alive connections
with old versions of MSIE, once a POST request is received.
The value safari disables keep-alive connections
with Safari and Safari-like browsers on macOS and macOS-like
operating systems.
The value none enables keep-alive connections
with all browsers.

Prior to version 1.1.18, the value safari matched
all Safari and Safari-like browsers on all operating systems, and
keep-alive connections with them were disabled by default.

Syntax: keepalive_requests number;
Default:
keepalive_requests 1000;
Context: http, server, location

This directive appeared in version 0.8.0.

Sets the maximum number of requests that can be
served through one keep-alive connection.
After the maximum number of requests are made, the connection is closed.

Closing connections periodically is necessary to free
per-connection memory allocations.
Therefore, using too high maximum number of requests
could result in excessive memory usage and not recommended.

Prior to version 1.19.10, the default value was 100.

Syntax: keepalive_time time;
Default:
keepalive_time 1h;
Context: http, server, location

This directive appeared in version 1.19.10.

Limits the maximum time during which
requests can be processed through one keep-alive connection.
After this time is reached, the connection is closed
following the subsequent request processing.

Syntax: keepalive_timeout
timeout
[header_timeout];
Default:
keepalive_timeout 75s;
Context: http, server, location

The first parameter sets a timeout during which a keep-alive
client connection will stay open on the server side.
The zero value disables keep-alive client connections.
The optional second parameter sets a value in the
“Keep-Alive: timeout=time
response header field.
Two parameters may differ.

The
“Keep-Alive: timeout=time
header field is recognized by Mozilla and Konqueror.
MSIE closes keep-alive connections by itself in about 60 seconds.

Syntax: large_client_header_buffers number size;
Default:
large_client_header_buffers 4 8k;
Context: http, server

Sets the maximum number and size of
buffers used for reading large client request header.
A request line cannot exceed the size of one buffer, or the
414 (Request-URI Too Large)
error is returned to the client.
A request header field cannot exceed the size of one buffer as well, or the
400 (Bad Request)
error is returned to the client.
Buffers are allocated only on demand.
By default, the buffer size is equal to 8K bytes.
If after the end of request processing a connection is transitioned
into the keep-alive state, these buffers are released.

If the directive is specified on the server level,
the value from the default server can be used.
Details are provided in the
“Virtual
server selection” section.

Syntax: limit_except method ... { ... }
Default:

Context: location

Limits allowed HTTP methods inside a location.
The method parameter can be one of the following:
GET,
HEAD,
POST,
PUT,
DELETE,
MKCOL,
COPY,
MOVE,
OPTIONS,
PROPFIND,
PROPPATCH,
LOCK,
UNLOCK,
or
PATCH.
Allowing the GET method makes the
HEAD method also allowed.
Access to other methods can be limited using the
ngx_http_access_module,
ngx_http_auth_basic_module,
and
ngx_http_auth_jwt_module
(1.13.10)
modules directives:

limit_except GET {
    allow 192.168.1.0/32;
    deny  all;
}

Please note that this will limit access to all methods
except GET and HEAD.

Syntax: limit_rate rate;
Default:
limit_rate 0;
Context: http, server, location, if in location

Limits the rate of response transmission to a client.
The rate is specified in bytes per second.
The zero value disables rate limiting.

The limit is set per a request, and so if a client simultaneously opens
two connections, the overall rate will be twice as much
as the specified limit.

Parameter value can contain variables (1.17.0).
It may be useful in cases where rate should be limited
depending on a certain condition:

map $slow $rate {
    1     4k;
    2     8k;
}

limit_rate $rate;

Rate limit can also be set in the
$limit_rate variable,
however, since version 1.17.0, this method is not recommended:

server {

    if ($slow) {
        set $limit_rate 4k;
    }

    ...
}

Rate limit can also be set in the
“X-Accel-Limit-Rate” header field of a proxied server response.
This capability can be disabled using the
proxy_ignore_headers,
fastcgi_ignore_headers,
uwsgi_ignore_headers,
and
scgi_ignore_headers
directives.

Syntax: limit_rate_after size;
Default:
limit_rate_after 0;
Context: http, server, location, if in location

This directive appeared in version 0.8.0.

Sets the initial amount after which the further transmission
of a response to a client will be rate limited.
Parameter value can contain variables (1.17.0).

Example:

location /flv/ {
    flv;
    limit_rate_after 500k;
    limit_rate       50k;
}
Syntax: lingering_close
off |
on |
always;
Default:
lingering_close on;
Context: http, server, location

This directive appeared in versions 1.1.0 and 1.0.6.

Controls how nginx closes client connections.

The default value “on” instructs nginx to
wait for and
process additional data from a client
before fully closing a connection, but only
if heuristics suggests that a client may be sending more data.

The value “always” will cause nginx to unconditionally
wait for and process additional client data.

The value “off” tells nginx to never wait for
more data and close the connection immediately.
This behavior breaks the protocol and should not be used under normal
circumstances.

To control closing
HTTP/2 connections,
the directive must be specified on the server level (1.19.1).

Syntax: lingering_time time;
Default:
lingering_time 30s;
Context: http, server, location

When lingering_close is in effect,
this directive specifies the maximum time during which nginx
will process (read and ignore) additional data coming from a client.
After that, the connection will be closed, even if there will be
more data.

Syntax: lingering_timeout time;
Default:
lingering_timeout 5s;
Context: http, server, location

When lingering_close is in effect, this directive specifies
the maximum waiting time for more client data to arrive.
If data are not received during this time, the connection is closed.
Otherwise, the data are read and ignored, and nginx starts waiting
for more data again.
The “wait-read-ignore” cycle is repeated, but no longer than specified by the
lingering_time directive.

Syntax: listen
address[:port]
[default_server]
[ssl]
[http2 | spdy]
[proxy_protocol]
[setfib=number]
[fastopen=number]
[backlog=number]
[rcvbuf=size]
[sndbuf=size]
[accept_filter=filter]
[deferred]
[bind]
[ipv6only=on|off]
[reuseport]
[so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];

listen
port
[default_server]
[ssl]
[http2 | spdy]
[proxy_protocol]
[setfib=number]
[fastopen=number]
[backlog=number]
[rcvbuf=size]
[sndbuf=size]
[accept_filter=filter]
[deferred]
[bind]
[ipv6only=on|off]
[reuseport]
[so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];

listen
unix:path
[default_server]
[ssl]
[http2 | spdy]
[proxy_protocol]
[backlog=number]
[rcvbuf=size]
[sndbuf=size]
[accept_filter=filter]
[deferred]
[bind]
[so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
Default:
listen *:80 | *:8000;
Context: server

Sets the address and port for IP,
or the path for a UNIX-domain socket on which
the server will accept requests.
Both address and port,
or only address or only port can be specified.
An address may also be a hostname, for example:

listen 127.0.0.1:8000;
listen 127.0.0.1;
listen 8000;
listen *:8000;
listen localhost:8000;

IPv6 addresses (0.7.36) are specified in square brackets:

listen [::]:8000;
listen [::1];

UNIX-domain sockets (0.8.21) are specified with the “unix:
prefix:

listen unix:/var/run/nginx.sock;

If only address is given, the port 80 is used.

If the directive is not present then either *:80 is used
if nginx runs with the superuser privileges, or *:8000
otherwise.

The default_server parameter, if present,
will cause the server to become the default server for the specified
address:port pair.
If none of the directives have the default_server
parameter then the first server with the
address:port pair will be
the default server for this pair.

In versions prior to 0.8.21 this parameter is named simply
default.

The ssl parameter (0.7.14) allows specifying that all
connections accepted on this port should work in SSL mode.
This allows for a more compact configuration for the server that
handles both HTTP and HTTPS requests.

The http2 parameter (1.9.5) configures the port to accept
HTTP/2 connections.
Normally, for this to work the ssl parameter should be
specified as well, but nginx can also be configured to accept HTTP/2
connections without SSL.

The spdy parameter (1.3.15-1.9.4) allows accepting
SPDY connections on this port.
Normally, for this to work the ssl parameter should be
specified as well, but nginx can also be configured to accept SPDY
connections without SSL.

The proxy_protocol parameter (1.5.12)
allows specifying that all connections accepted on this port should use the
PROXY
protocol.

The PROXY protocol version 2 is supported since version 1.13.11.

The listen directive
can have several additional parameters specific to socket-related system calls.
These parameters can be specified in any
listen directive, but only once for a given
address:port pair.

In versions prior to 0.8.21, they could only be
specified in the listen directive together with the
default parameter.

setfib=number
this parameter (0.8.44) sets the associated routing table, FIB
(the SO_SETFIB option) for the listening socket.
This currently works only on FreeBSD.
fastopen=number
enables
“TCP Fast Open”
for the listening socket (1.5.8) and
limits
the maximum length for the queue of connections that have not yet completed
the three-way handshake.

Do not enable this feature unless the server can handle
receiving the

same SYN packet with data more than once.

backlog=number
sets the backlog parameter in the
listen() call that limits
the maximum length for the queue of pending connections.
By default,
backlog is set to -1 on FreeBSD, DragonFly BSD, and macOS,
and to 511 on other platforms.
rcvbuf=size
sets the receive buffer size
(the SO_RCVBUF option) for the listening socket.
sndbuf=size
sets the send buffer size
(the SO_SNDBUF option) for the listening socket.
accept_filter=filter
sets the name of accept filter
(the SO_ACCEPTFILTER option) for the listening socket
that filters incoming connections before passing them to
accept().
This works only on FreeBSD and NetBSD 5.0+.
Possible values are
dataready
and
httpready.
deferred
instructs to use a deferred accept()
(the TCP_DEFER_ACCEPT socket option) on Linux.
bind
instructs to make a separate bind() call for a given
address:port pair.
This is useful because if there are several listen
directives with the same port but different addresses, and one of the
listen directives listens on all addresses
for the given port (*:port), nginx
will bind() only to *:port.
It should be noted that the getsockname() system call will be
made in this case to determine the address that accepted the connection.
If the setfib,
fastopen,
backlog, rcvbuf,
sndbuf, accept_filter,
deferred, ipv6only,
reuseport,
or so_keepalive parameters
are used then for a given
address:port pair
a separate bind() call will always be made.
ipv6only=on|off
this parameter (0.7.42) determines
(via the IPV6_V6ONLY socket option)
whether an IPv6 socket listening on a wildcard address [::]
will accept only IPv6 connections or both IPv6 and IPv4 connections.
This parameter is turned on by default.
It can only be set once on start.

Prior to version 1.3.4,
if this parameter was omitted then the operating system’s settings were
in effect for the socket.

reuseport
this parameter (1.9.1) instructs to create an individual listening socket
for each worker process
(using the
SO_REUSEPORT socket option on Linux 3.9+ and DragonFly BSD,
or SO_REUSEPORT_LB on FreeBSD 12+), allowing a kernel
to distribute incoming connections between worker processes.
This currently works only on Linux 3.9+, DragonFly BSD,
and FreeBSD 12+ (1.15.1).

Inappropriate use of this option may have its security
implications.

so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]
this parameter (1.1.11) configures the “TCP keepalive” behavior
for the listening socket.
If this parameter is omitted then the operating system’s settings will be
in effect for the socket.
If it is set to the value “on”, the
SO_KEEPALIVE option is turned on for the socket.
If it is set to the value “off”, the
SO_KEEPALIVE option is turned off for the socket.
Some operating systems support setting of TCP keepalive parameters on
a per-socket basis using the TCP_KEEPIDLE,
TCP_KEEPINTVL, and TCP_KEEPCNT socket options.
On such systems (currently, Linux 2.4+, NetBSD 5+, and
FreeBSD 9.0-STABLE), they can be configured
using the keepidle, keepintvl, and
keepcnt parameters.
One or two parameters may be omitted, in which case the system default setting
for the corresponding socket option will be in effect.
For example,

so_keepalive=30m::10

will set the idle timeout (TCP_KEEPIDLE) to 30 minutes,
leave the probe interval (TCP_KEEPINTVL) at its system default,
and set the probes count (TCP_KEEPCNT) to 10 probes.

Example:

listen 127.0.0.1 default_server accept_filter=dataready backlog=1024;
Syntax: location [
= |
~ |
~* |
^~
] uri { ... }

location @name { ... }
Default:

Context: server, location

Sets configuration depending on a request URI.

The matching is performed against a normalized URI,
after decoding the text encoded in the “%XX” form,
resolving references to relative path components “.
and “..”, and possible
compression of two or more
adjacent slashes into a single slash.

A location can either be defined by a prefix string, or by a regular expression.
Regular expressions are specified with the preceding
~*” modifier (for case-insensitive matching), or the
~” modifier (for case-sensitive matching).
To find location matching a given request, nginx first checks
locations defined using the prefix strings (prefix locations).
Among them, the location with the longest matching
prefix is selected and remembered.
Then regular expressions are checked, in the order of their appearance
in the configuration file.
The search of regular expressions terminates on the first match,
and the corresponding configuration is used.
If no match with a regular expression is found then the
configuration of the prefix location remembered earlier is used.

location blocks can be nested, with some exceptions
mentioned below.

For case-insensitive operating systems such as macOS and Cygwin,
matching with prefix strings ignores a case (0.7.7).
However, comparison is limited to one-byte locales.

Regular expressions can contain captures (0.7.40) that can later
be used in other directives.

If the longest matching prefix location has the “^~” modifier
then regular expressions are not checked.

Also, using the “=” modifier it is possible to define
an exact match of URI and location.
If an exact match is found, the search terminates.
For example, if a “/” request happens frequently,
defining “location = /” will speed up the processing
of these requests, as search terminates right after the first
comparison.
Such a location cannot obviously contain nested locations.

In versions from 0.7.1 to 0.8.41, if a request matched the prefix
location without the “=” and “^~
modifiers, the search also terminated and regular expressions were
not checked.

Let’s illustrate the above by an example:

location = / {
    [ configuration A ]
}

location / {
    [ configuration B ]
}

location /documents/ {
    [ configuration C ]
}

location ^~ /images/ {
    [ configuration D ]
}

location ~* .(gif|jpg|jpeg)$ {
    [ configuration E ]
}

The “/” request will match configuration A,
the “/index.html” request will match configuration B,
the “/documents/document.html” request will match
configuration C,
the “/images/1.gif” request will match configuration D, and
the “/documents/1.jpg” request will match configuration E.

The “@” prefix defines a named location.
Such a location is not used for a regular request processing, but instead
used for request redirection.
They cannot be nested, and cannot contain nested locations.

If a location is defined by a prefix string that ends with the slash character,
and requests are processed by one of
proxy_pass,
fastcgi_pass,
uwsgi_pass,
scgi_pass,
memcached_pass, or
grpc_pass,
then the special processing is performed.
In response to a request with URI equal to this string,
but without the trailing slash,
a permanent redirect with the code 301 will be returned to the requested URI
with the slash appended.
If this is not desired, an exact match of the URI and location could be
defined like this:

location /user/ {
    proxy_pass http://user.example.com;
}

location = /user {
    proxy_pass http://login.example.com;
}
Syntax: log_not_found on | off;
Default:
log_not_found on;
Context: http, server, location

Enables or disables logging of errors about not found files into
error_log.

Syntax: log_subrequest on | off;
Default:
log_subrequest off;
Context: http, server, location

Enables or disables logging of subrequests into
access_log.

Syntax: max_ranges number;
Default:

Context: http, server, location

This directive appeared in version 1.1.2.

Limits the maximum allowed number of ranges in byte-range requests.
Requests that exceed the limit are processed as if there were no
byte ranges specified.
By default, the number of ranges is not limited.
The zero value disables the byte-range support completely.

Syntax: merge_slashes on | off;
Default:
merge_slashes on;
Context: http, server

Enables or disables compression of two or more adjacent slashes
in a URI into a single slash.

Note that compression is essential for the correct matching of prefix string
and regular expression locations.
Without it, the “//scripts/one.php” request would not match

location /scripts/ {
    ...
}

and might be processed as a static file.
So it gets converted to “/scripts/one.php”.

Turning the compression off can become necessary if a URI
contains base64-encoded names, since base64 uses the “/
character internally.
However, for security considerations, it is better to avoid turning
the compression off.

If the directive is specified on the server level,
the value from the default server can be used.
Details are provided in the
“Virtual
server selection” section.

Syntax: msie_padding on | off;
Default:
msie_padding on;
Context: http, server, location

Enables or disables adding comments to responses for MSIE clients with status
greater than 400 to increase the response size to 512 bytes.

Syntax: msie_refresh on | off;
Default:
msie_refresh off;
Context: http, server, location

Enables or disables issuing refreshes instead of redirects for MSIE clients.

Syntax: open_file_cache off;
open_file_cache
max=N
[inactive=time];
Default:
open_file_cache off;
Context: http, server, location

Configures a cache that can store:

  • open file descriptors, their sizes and modification times;
  • information on existence of directories;
  • file lookup errors, such as “file not found”, “no read permission”,
    and so on.

    Caching of errors should be enabled separately by the
    open_file_cache_errors
    directive.

The directive has the following parameters:

max
sets the maximum number of elements in the cache;
on cache overflow the least recently used (LRU) elements are removed;
inactive
defines a time after which an element is removed from the cache
if it has not been accessed during this time;
by default, it is 60 seconds;
off
disables the cache.

Example:

open_file_cache          max=1000 inactive=20s;
open_file_cache_valid    30s;
open_file_cache_min_uses 2;
open_file_cache_errors   on;
Syntax: open_file_cache_errors on | off;
Default:
open_file_cache_errors off;
Context: http, server, location

Enables or disables caching of file lookup errors by
open_file_cache.

Syntax: open_file_cache_min_uses number;
Default:
open_file_cache_min_uses 1;
Context: http, server, location

Sets the minimum number of file accesses during
the period configured by the inactive parameter
of the open_file_cache directive, required for a file
descriptor to remain open in the cache.

Syntax: open_file_cache_valid time;
Default:
open_file_cache_valid 60s;
Context: http, server, location

Sets a time after which
open_file_cache
elements should be validated.

Syntax: output_buffers number size;
Default:
output_buffers 2 32k;
Context: http, server, location

Sets the number and size of the
buffers used for reading a response from a disk.

Prior to version 1.9.5, the default value was 1 32k.

Syntax: port_in_redirect on | off;
Default:
port_in_redirect on;
Context: http, server, location

Enables or disables specifying the port in
absolute redirects issued by nginx.

The use of the primary server name in redirects is controlled by
the server_name_in_redirect directive.

Syntax: postpone_output size;
Default:
postpone_output 1460;
Context: http, server, location

If possible, the transmission of client data will be postponed until
nginx has at least size bytes of data to send.
The zero value disables postponing data transmission.

Syntax: read_ahead size;
Default:
read_ahead 0;
Context: http, server, location

Sets the amount of pre-reading for the kernel when working with file.

On Linux, the
posix_fadvise(0, 0, 0, POSIX_FADV_SEQUENTIAL)
system call is used, and so the size parameter is ignored.

On FreeBSD, the
fcntl(O_READAHEAD,
size)
system call, supported since FreeBSD 9.0-CURRENT, is used.
FreeBSD 7 has to be
patched.

Syntax: recursive_error_pages on | off;
Default:
recursive_error_pages off;
Context: http, server, location

Enables or disables doing several redirects using the
error_page
directive.
The number of such redirects is limited.

Syntax: request_pool_size size;
Default:
request_pool_size 4k;
Context: http, server

Allows accurate tuning of per-request memory allocations.
This directive has minimal impact on performance
and should not generally be used.

Syntax: reset_timedout_connection on | off;
Default:
reset_timedout_connection off;
Context: http, server, location

Enables or disables resetting timed out connections
and connections
closed
with the non-standard code 444 (1.15.2).
The reset is performed as follows.
Before closing a socket, the
SO_LINGER
option is set on it with a timeout value of 0.
When the socket is closed, TCP RST is sent to the client, and all memory
occupied by this socket is released.
This helps avoid keeping an already closed socket with filled buffers
in a FIN_WAIT1 state for a long time.

It should be noted that timed out keep-alive connections are
closed normally.

Syntax: resolver
address ...
[valid=time]
[ipv4=on|off]
[ipv6=on|off]
[status_zone=zone];
Default:

Context: http, server, location

Configures name servers used to resolve names of upstream servers
into addresses, for example:

resolver 127.0.0.1 [::1]:5353;

The address can be specified as a domain name or IP address,
with an optional port (1.3.1, 1.2.2).
If port is not specified, the port 53 is used.
Name servers are queried in a round-robin fashion.

Before version 1.1.7, only a single name server could be configured.
Specifying name servers using IPv6 addresses is supported
starting from versions 1.3.1 and 1.2.2.

By default, nginx will look up both IPv4 and IPv6 addresses while resolving.
If looking up of IPv4 or IPv6 addresses is not desired,
the ipv4=off (1.23.1) or
the ipv6=off parameter can be specified.

Resolving of names into IPv6 addresses is supported
starting from version 1.5.8.

By default, nginx caches answers using the TTL value of a response.
An optional valid parameter allows overriding it:

resolver 127.0.0.1 [::1]:5353 valid=30s;

Before version 1.1.9, tuning of caching time was not possible,
and nginx always cached answers for the duration of 5 minutes.

To prevent DNS spoofing, it is recommended
configuring DNS servers in a properly secured trusted local network.

The optional status_zone parameter (1.17.1)
enables
collection
of DNS server statistics of requests and responses
in the specified zone.
The parameter is available as part of our
commercial subscription.

Syntax: resolver_timeout time;
Default:
resolver_timeout 30s;
Context: http, server, location

Sets a timeout for name resolution, for example:

resolver_timeout 5s;
Syntax: root path;
Default:
root html;
Context: http, server, location, if in location

Sets the root directory for requests.
For example, with the following configuration

location /i/ {
    root /data/w3;
}

The /data/w3/i/top.gif file will be sent in response to
the “/i/top.gif” request.

The path value can contain variables,
except $document_root and $realpath_root.

A path to the file is constructed by merely adding a URI to the value
of the root directive.
If a URI has to be modified, the
alias directive should be used.

Syntax: satisfy all | any;
Default:
satisfy all;
Context: http, server, location

Allows access if all (all) or at least one
(any) of the
ngx_http_access_module,
ngx_http_auth_basic_module,
ngx_http_auth_request_module,
or
ngx_http_auth_jwt_module
modules allow access.

Example:

location / {
    satisfy any;

    allow 192.168.1.0/32;
    deny  all;

    auth_basic           "closed site";
    auth_basic_user_file conf/htpasswd;
}
Syntax: send_lowat size;
Default:
send_lowat 0;
Context: http, server, location

If the directive is set to a non-zero value, nginx will try to minimize
the number of send operations on client sockets by using either
NOTE_LOWAT flag of the
kqueue method
or the SO_SNDLOWAT socket option.
In both cases the specified size is used.

This directive is ignored on Linux, Solaris, and Windows.

Syntax: send_timeout time;
Default:
send_timeout 60s;
Context: http, server, location

Sets a timeout for transmitting a response to the client.
The timeout is set only between two successive write operations,
not for the transmission of the whole response.
If the client does not receive anything within this time,
the connection is closed.

Syntax: sendfile on | off;
Default:
sendfile off;
Context: http, server, location, if in location

Enables or disables the use of
sendfile().

Starting from nginx 0.8.12 and FreeBSD 5.2.1,
aio can be used to pre-load data
for sendfile():

location /video/ {
    sendfile       on;
    tcp_nopush     on;
    aio            on;
}

In this configuration, sendfile() is called with
the SF_NODISKIO flag which causes it not to block on disk I/O,
but, instead, report back that the data are not in memory.
nginx then initiates an asynchronous data load by reading one byte.
On the first read, the FreeBSD kernel loads the first 128K bytes
of a file into memory, although next reads will only load data in 16K chunks.
This can be changed using the
read_ahead directive.

Before version 1.7.11, pre-loading could be enabled with
aio sendfile;.

Syntax: sendfile_max_chunk size;
Default:
sendfile_max_chunk 2m;
Context: http, server, location

Limits the amount of data that can be
transferred in a single sendfile() call.
Without the limit, one fast connection may seize the worker process entirely.

Prior to version 1.21.4, by default there was no limit.

Syntax: server { ... }
Default:

Context: http

Sets configuration for a virtual server.
There is no clear separation between IP-based (based on the IP address)
and name-based (based on the “Host” request header field)
virtual servers.
Instead, the listen directives describe all
addresses and ports that should accept connections for the server, and the
server_name directive lists all server names.
Example configurations are provided in the
“How nginx processes a request” document.

Syntax: server_name name ...;
Default:
server_name "";
Context: server

Sets names of a virtual server, for example:

server {
    server_name example.com www.example.com;
}

The first name becomes the primary server name.

Server names can include an asterisk (“*”)
replacing the first or last part of a name:

server {
    server_name example.com *.example.com www.example.*;
}

Such names are called wildcard names.

The first two of the names mentioned above can be combined in one:

server {
    server_name .example.com;
}

It is also possible to use regular expressions in server names,
preceding the name with a tilde (“~”):

server {
    server_name www.example.com ~^wwwd+.example.com$;
}

Regular expressions can contain captures (0.7.40) that can later
be used in other directives:

server {
    server_name ~^(www.)?(.+)$;

    location / {
        root /sites/$2;
    }
}

server {
    server_name _;

    location / {
        root /sites/default;
    }
}

Named captures in regular expressions create variables (0.8.25)
that can later be used in other directives:

server {
    server_name ~^(www.)?(?<domain>.+)$;

    location / {
        root /sites/$domain;
    }
}

server {
    server_name _;

    location / {
        root /sites/default;
    }
}

If the directive’s parameter is set to “$hostname” (0.9.4), the
machine’s hostname is inserted.

It is also possible to specify an empty server name (0.7.11):

server {
    server_name www.example.com "";
}

It allows this server to process requests without the “Host”
header field — instead of the default server — for the given address:port pair.
This is the default setting.

Before 0.8.48, the machine’s hostname was used by default.

During searching for a virtual server by name,
if the name matches more than one of the specified variants,
(e.g. both a wildcard name and regular expression match), the first matching
variant will be chosen, in the following order of priority:

  1. the exact name
  2. the longest wildcard name starting with an asterisk,
    e.g. “*.example.com
  3. the longest wildcard name ending with an asterisk,
    e.g. “mail.*
  4. the first matching regular expression
    (in order of appearance in the configuration file)

Detailed description of server names is provided in a separate
Server names document.

Syntax: server_name_in_redirect on | off;
Default:
server_name_in_redirect off;
Context: http, server, location

Enables or disables the use of the primary server name, specified by the
server_name directive,
in absolute redirects issued by nginx.
When the use of the primary server name is disabled, the name from the
“Host” request header field is used.
If this field is not present, the IP address of the server is used.

The use of a port in redirects is controlled by
the port_in_redirect directive.

Syntax: server_names_hash_bucket_size size;
Default:
server_names_hash_bucket_size 32|64|128;
Context: http

Sets the bucket size for the server names hash tables.
The default value depends on the size of the processor’s cache line.
The details of setting up hash tables are provided in a separate
document.

Syntax: server_names_hash_max_size size;
Default:
server_names_hash_max_size 512;
Context: http

Sets the maximum size of the server names hash tables.
The details of setting up hash tables are provided in a separate
document.

Syntax: server_tokens
on |
off |
build |
string;
Default:
server_tokens on;
Context: http, server, location

Enables or disables emitting nginx version on error pages and in the
“Server” response header field.

The build parameter (1.11.10) enables emitting
a build name
along with nginx version.

Additionally, as part of our
commercial subscription,
starting from version 1.9.13
the signature on error pages and
the “Server” response header field value
can be set explicitly using the string with variables.
An empty string disables the emission of the “Server” field.

Syntax: subrequest_output_buffer_size size;
Default:
subrequest_output_buffer_size 4k|8k;
Context: http, server, location

This directive appeared in version 1.13.10.

Sets the size of the buffer used for
storing the response body of a subrequest.
By default, the buffer size is equal to one memory page.
This is either 4K or 8K, depending on a platform.
It can be made smaller, however.

The directive is applicable only for subrequests
with response bodies saved into memory.
For example, such subrequests are created by
SSI.

Syntax: tcp_nodelay on | off;
Default:
tcp_nodelay on;
Context: http, server, location

Enables or disables the use of the TCP_NODELAY option.
The option is enabled when a connection is transitioned into the
keep-alive state.
Additionally, it is enabled on SSL connections,
for unbuffered proxying,
and for WebSocket proxying.

Syntax: tcp_nopush on | off;
Default:
tcp_nopush off;
Context: http, server, location

Enables or disables the use of
the TCP_NOPUSH socket option on FreeBSD
or the TCP_CORK socket option on Linux.
The options are enabled only when sendfile is used.
Enabling the option allows

  • sending the response header and the beginning of a file in one packet,
    on Linux and FreeBSD 4.*;
  • sending a file in full packets.
Syntax: try_files file ... uri;
try_files file ... =code;
Default:

Context: server, location

Checks the existence of files in the specified order and uses
the first found file for request processing; the processing
is performed in the current context.
The path to a file is constructed from the
file parameter
according to the
root and alias directives.
It is possible to check directory’s existence by specifying
a slash at the end of a name, e.g. “$uri/”.
If none of the files were found, an internal redirect to the
uri specified in the last parameter is made.
For example:

location /images/ {
    try_files $uri /images/default.gif;
}

location = /images/default.gif {
    expires 30s;
}

The last parameter can also point to a named location,
as shown in examples below.
Starting from version 0.7.51, the last parameter can also be a
code:

location / {
    try_files $uri $uri/index.html $uri.html =404;
}

Example in proxying Mongrel:

location / {
    try_files /system/maintenance.html
              $uri $uri/index.html $uri.html
              @mongrel;
}

location @mongrel {
    proxy_pass http://mongrel;
}

Example for Drupal/FastCGI:

location / {
    try_files $uri $uri/ @drupal;
}

location ~ .php$ {
    try_files $uri @drupal;

    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;
    fastcgi_param SCRIPT_NAME     $fastcgi_script_name;
    fastcgi_param QUERY_STRING    $args;

    ... other fastcgi_param's
}

location @drupal {
    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to/index.php;
    fastcgi_param SCRIPT_NAME     /index.php;
    fastcgi_param QUERY_STRING    q=$uri&$args;

    ... other fastcgi_param's
}

In the following example,

location / {
    try_files $uri $uri/ @drupal;
}

the try_files directive is equivalent to

location / {
    error_page 404 = @drupal;
    log_not_found off;
}

And here,

location ~ .php$ {
    try_files $uri @drupal;

    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;

    ...
}

try_files checks the existence of the PHP file
before passing the request to the FastCGI server.

Example for WordPress and Joomla:

location / {
    try_files $uri $uri/ @wordpress;
}

location ~ .php$ {
    try_files $uri @wordpress;

    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;
    ... other fastcgi_param's
}

location @wordpress {
    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to/index.php;
    ... other fastcgi_param's
}
Syntax: types { ... }
Default:
types {
    text/html  html;
    image/gif  gif;
    image/jpeg jpg;
}
Context: http, server, location

Maps file name extensions to MIME types of responses.
Extensions are case-insensitive.
Several extensions can be mapped to one type, for example:

types {
    application/octet-stream bin exe dll;
    application/octet-stream deb;
    application/octet-stream dmg;
}

A sufficiently full mapping table is distributed with nginx in the
conf/mime.types file.

To make a particular location emit the
application/octet-stream
MIME type for all requests, the following configuration can be used:

location /download/ {
    types        { }
    default_type application/octet-stream;
}
Syntax: types_hash_bucket_size size;
Default:
types_hash_bucket_size 64;
Context: http, server, location

Sets the bucket size for the types hash tables.
The details of setting up hash tables are provided in a separate
document.

Prior to version 1.5.13,
the default value depended on the size of the processor’s cache line.

Syntax: types_hash_max_size size;
Default:
types_hash_max_size 1024;
Context: http, server, location

Sets the maximum size of the types hash tables.
The details of setting up hash tables are provided in a separate
document.

Syntax: underscores_in_headers on | off;
Default:
underscores_in_headers off;
Context: http, server

Enables or disables the use of underscores in client request header fields.
When the use of underscores is disabled, request header fields whose names
contain underscores are
marked as invalid and become subject to the
ignore_invalid_headers directive.

If the directive is specified on the server level,
the value from the default server can be used.
Details are provided in the
“Virtual
server selection” section.

Syntax: variables_hash_bucket_size size;
Default:
variables_hash_bucket_size 64;
Context: http

Sets the bucket size for the variables hash table.
The details of setting up hash tables are provided in a separate
document.

Syntax: variables_hash_max_size size;
Default:
variables_hash_max_size 1024;
Context: http

Sets the maximum size of the variables hash table.
The details of setting up hash tables are provided in a separate
document.

Prior to version 1.5.13, the default value was 512.

Embedded Variables

The ngx_http_core_module module supports embedded variables
with names matching the Apache Server variables.
First of all, these are variables representing client request header
fields, such as $http_user_agent, $http_cookie,
and so on.
Also there are other variables:

$arg_name
argument name in the request line
$args
arguments in the request line
$binary_remote_addr
client address in a binary form, value’s length is always 4 bytes
for IPv4 addresses or 16 bytes for IPv6 addresses
$body_bytes_sent
number of bytes sent to a client, not counting the response header;
this variable is compatible with the “%B” parameter of the
mod_log_config
Apache module
$bytes_sent
number of bytes sent to a client (1.3.8, 1.2.5)
$connection
connection serial number (1.3.8, 1.2.5)
$connection_requests
current number of requests made through a connection (1.3.8, 1.2.5)
$connection_time
connection time in seconds with a milliseconds resolution (1.19.10)
$content_length
“Content-Length” request header field
$content_type
“Content-Type” request header field
$cookie_name
the name cookie
$document_root
root or alias directive’s value
for the current request
$document_uri
same as $uri
$host
in this order of precedence:
host name from the request line, or
host name from the “Host” request header field, or
the server name matching a request
$hostname
host name
$http_name
arbitrary request header field;
the last part of a variable name is the field name converted
to lower case with dashes replaced by underscores
$https
on
if connection operates in SSL mode,
or an empty string otherwise
$is_args
?” if a request line has arguments,
or an empty string otherwise
$limit_rate
setting this variable enables response rate limiting;
see limit_rate
$msec
current time in seconds with the milliseconds resolution (1.3.9, 1.2.6)
$nginx_version
nginx version
$pid
PID of the worker process
$pipe
p” if request was pipelined, “.
otherwise (1.3.12, 1.2.7)
$proxy_protocol_addr
client address from the PROXY protocol header (1.5.12)

The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter
in the listen directive.

$proxy_protocol_port
client port from the PROXY protocol header (1.11.0)

The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter
in the listen directive.

$proxy_protocol_server_addr
server address from the PROXY protocol header (1.17.6)

The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter
in the listen directive.

$proxy_protocol_server_port
server port from the PROXY protocol header (1.17.6)

The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter
in the listen directive.

$proxy_protocol_tlv_name
TLV from the PROXY Protocol header (1.23.2).
The name can be a TLV type name or its numeric value.
In the latter case, the value is hexadecimal
and should be prefixed with 0x:

$proxy_protocol_tlv_alpn
$proxy_protocol_tlv_0x01

SSL TLVs can also be accessed by TLV type name
or its numeric value,
both prefixed by ssl_:

$proxy_protocol_tlv_ssl_version
$proxy_protocol_tlv_ssl_0x21

The following TLV type names are supported:

  • alpn (0x01) —
    upper layer protocol used over the connection
  • authority (0x02) —
    host name value passed by the client
  • unique_id (0x05) —
    unique connection id
  • netns (0x30) —
    name of the namespace
  • ssl (0x20) —
    binary SSL TLV structure

The following SSL TLV type names are supported:

  • ssl_version (0x21) —
    SSL version used in client connection
  • ssl_cn (0x22) —
    SSL certificate Common Name
  • ssl_cipher (0x23) —
    name of the used cipher
  • ssl_sig_alg (0x24) —
    algorithm used to sign the certificate
  • ssl_key_alg (0x25) —
    public-key algorithm

Also, the following special SSL TLV type name is supported:

  • ssl_verify —
    client SSL certificate verification result,
    0 if the client presented a certificate
    and it was successfully verified,
    non-zero otherwise.

The PROXY protocol must be previously enabled by setting the
proxy_protocol parameter
in the listen directive.

$query_string
same as $args
$realpath_root
an absolute pathname corresponding to the
root or alias directive’s value
for the current request,
with all symbolic links resolved to real paths
$remote_addr
client address
$remote_port
client port
$remote_user
user name supplied with the Basic authentication
$request
full original request line
$request_body
request body

The variable’s value is made available in locations
processed by the
proxy_pass,
fastcgi_pass,
uwsgi_pass,
and
scgi_pass
directives when the request body was read to
a memory buffer.

$request_body_file
name of a temporary file with the request body

At the end of processing, the file needs to be removed.
To always write the request body to a file,
client_body_in_file_only needs to be enabled.
When the name of a temporary file is passed in a proxied request
or in a request to a FastCGI/uwsgi/SCGI server,
passing the request body should be disabled by the

proxy_pass_request_body off,

fastcgi_pass_request_body off,

uwsgi_pass_request_body off, or

scgi_pass_request_body off
directives, respectively.

$request_completion
OK” if a request has completed,
or an empty string otherwise
$request_filename
file path for the current request, based on the
root or alias
directives, and the request URI
$request_id
unique request identifier
generated from 16 random bytes, in hexadecimal (1.11.0)
$request_length
request length (including request line, header, and request body)
(1.3.12, 1.2.7)
$request_method
request method, usually
GET” or “POST
$request_time
request processing time in seconds with a milliseconds resolution
(1.3.9, 1.2.6);
time elapsed since the first bytes were read from the client
$request_uri
full original request URI (with arguments)
$scheme
request scheme, “http” or “https
$sent_http_name
arbitrary response header field;
the last part of a variable name is the field name converted
to lower case with dashes replaced by underscores
$sent_trailer_name
arbitrary field sent at the end of the response (1.13.2);
the last part of a variable name is the field name converted
to lower case with dashes replaced by underscores
$server_addr
an address of the server which accepted a request

Computing a value of this variable usually requires one system call.
To avoid a system call, the listen directives
must specify addresses and use the bind parameter.

$server_name
name of the server which accepted a request
$server_port
port of the server which accepted a request
$server_protocol
request protocol, usually
HTTP/1.0”,
HTTP/1.1”,
or
“HTTP/2.0”
$status
response status (1.3.2, 1.2.2)
$tcpinfo_rtt,
$tcpinfo_rttvar,
$tcpinfo_snd_cwnd,
$tcpinfo_rcv_space
information about the client TCP connection; available on systems
that support the TCP_INFO socket option
$time_iso8601
local time in the ISO 8601 standard format (1.3.12, 1.2.7)
$time_local
local time in the Common Log Format (1.3.12, 1.2.7)
$uri
current URI in request, normalized

The value of $uri may change during request processing,
e.g. when doing internal redirects, or when using index files.

Содержание

  1. Module ngx_http_core_module
  2. Directives
  3. Embedded Variables

Module ngx_http_core_module

Directives

Syntax: absolute_redirect on | off ;
Default:
Context: http , server , location

This directive appeared in version 1.11.8.

If disabled, redirects issued by nginx will be relative.

Syntax: aio on | off | threads [ = pool ];
Default:
Context: http , server , location

This directive appeared in version 0.8.11.

Enables or disables the use of asynchronous file I/O (AIO) on FreeBSD and Linux:

On FreeBSD, AIO can be used starting from FreeBSD 4.3. Prior to FreeBSD 11.0, AIO can either be linked statically into a kernel:

or loaded dynamically as a kernel loadable module:

On Linux, AIO can be used starting from kernel version 2.6.22. Also, it is necessary to enable directio, or otherwise reading will be blocking:

On Linux, directio can only be used for reading blocks that are aligned on 512-byte boundaries (or 4K for XFS). File’s unaligned end is read in blocking mode. The same holds true for byte range requests and for FLV requests not from the beginning of a file: reading of unaligned data at the beginning and end of a file will be blocking.

When both AIO and sendfile are enabled on Linux, AIO is used for files that are larger than or equal to the size specified in the directio directive, while sendfile is used for files of smaller sizes or when directio is disabled.

Finally, files can be read and sent using multi-threading (1.7.11), without blocking a worker process:

Read and send file operations are offloaded to threads of the specified pool. If the pool name is omitted, the pool with the name “ default ” is used. The pool name can also be set with variables:

By default, multi-threading is disabled, it should be enabled with the —with-threads configuration parameter. Currently, multi-threading is compatible only with the epoll, kqueue, and eventport methods. Multi-threaded sending of files is only supported on Linux.

See also the sendfile directive.

Syntax: aio_write on | off ;
Default:
Context: http , server , location

This directive appeared in version 1.9.13.

If aio is enabled, specifies whether it is used for writing files. Currently, this only works when using aio threads and is limited to writing temporary files with data received from proxied servers.

Syntax: alias path ;
Default:
Context: location

Defines a replacement for the specified location. For example, with the following configuration

on request of “ /i/top.gif ”, the file /data/w3/images/top.gif will be sent.

The path value can contain variables, except $document_root and $realpath_root .

If alias is used inside a location defined with a regular expression then such regular expression should contain captures and alias should refer to these captures (0.7.40), for example:

When location matches the last part of the directive’s value:

it is better to use the root directive instead:

Syntax: auth_delay time ;
Default:
Context: http , server , location

This directive appeared in version 1.17.10.

Delays processing of unauthorized requests with 401 response code to prevent timing attacks when access is limited by password, by the result of subrequest, or by JWT.

Syntax: chunked_transfer_encoding on | off ;
Default:
Context: http , server , location

Allows disabling chunked transfer encoding in HTTP/1.1. It may come in handy when using a software failing to support chunked encoding despite the standard’s requirement.

Syntax: client_body_buffer_size size ;
Default:
Context: http , server , location

Sets buffer size for reading client request body. In case the request body is larger than the buffer, the whole body or only its part is written to a temporary file. By default, buffer size is equal to two memory pages. This is 8K on x86, other 32-bit platforms, and x86-64. It is usually 16K on other 64-bit platforms.

Syntax: client_body_in_file_only on | clean | off ;
Default:
Context: http , server , location

Determines whether nginx should save the entire client request body into a file. This directive can be used during debugging, or when using the $request_body_file variable, or the $r->request_body_file method of the module ngx_http_perl_module.

When set to the value on , temporary files are not removed after request processing.

The value clean will cause the temporary files left after request processing to be removed.

Syntax: client_body_in_single_buffer on | off ;
Default:
Context: http , server , location

Determines whether nginx should save the entire client request body in a single buffer. The directive is recommended when using the $request_body variable, to save the number of copy operations involved.

Syntax: client_body_temp_path path [ level1 [ level2 [ level3 ]]];
Default:
Context: http , server , location

Defines a directory for storing temporary files holding client request bodies. Up to three-level subdirectory hierarchy can be used under the specified directory. For example, in the following configuration

a path to a temporary file might look like this:

Syntax: client_body_timeout time ;
Default:
Context: http , server , location

Defines a timeout for reading client request body. The timeout is set only for a period between two successive read operations, not for the transmission of the whole request body. If a client does not transmit anything within this time, the request is terminated with the 408 (Request Time-out) error.

Syntax: client_header_buffer_size size ;
Default:
Context: http , server

Sets buffer size for reading client request header. For most requests, a buffer of 1K bytes is enough. However, if a request includes long cookies, or comes from a WAP client, it may not fit into 1K. If a request line or a request header field does not fit into this buffer then larger buffers, configured by the large_client_header_buffers directive, are allocated.

If the directive is specified on the server level, the value from the default server can be used. Details are provided in the “Virtual server selection” section.

Syntax: client_header_timeout time ;
Default:
Context: http , server

Defines a timeout for reading client request header. If a client does not transmit the entire header within this time, the request is terminated with the 408 (Request Time-out) error.

Syntax: client_max_body_size size ;
Default:
Context: http , server , location

Sets the maximum allowed size of the client request body. If the size in a request exceeds the configured value, the 413 (Request Entity Too Large) error is returned to the client. Please be aware that browsers cannot correctly display this error. Setting size to 0 disables checking of client request body size.

Syntax: connection_pool_size size ;
Default:
Context: http , server

Allows accurate tuning of per-connection memory allocations. This directive has minimal impact on performance and should not generally be used. By default, the size is equal to 256 bytes on 32-bit platforms and 512 bytes on 64-bit platforms.

Prior to version 1.9.8, the default value was 256 on all platforms.

Syntax: default_type mime-type ;
Default:
Context: http , server , location

Defines the default MIME type of a response. Mapping of file name extensions to MIME types can be set with the types directive.

Syntax: directio size | off ;
Default:
Context: http , server , location

This directive appeared in version 0.7.7.

Enables the use of the O_DIRECT flag (FreeBSD, Linux), the F_NOCACHE flag (macOS), or the directio() function (Solaris), when reading files that are larger than or equal to the specified size . The directive automatically disables (0.7.15) the use of sendfile for a given request. It can be useful for serving large files:

or when using aio on Linux.

Syntax: directio_alignment size ;
Default:
Context: http , server , location

This directive appeared in version 0.8.11.

Sets the alignment for directio. In most cases, a 512-byte alignment is enough. However, when using XFS under Linux, it needs to be increased to 4K.

Syntax: disable_symlinks off ;
disable_symlinks on | if_not_owner [ from = part ];
Default:
Context: http , server , location

This directive appeared in version 1.1.15.

Determines how symbolic links should be treated when opening files:

off Symbolic links in the pathname are allowed and not checked. This is the default behavior. on If any component of the pathname is a symbolic link, access to a file is denied. if_not_owner Access to a file is denied if any component of the pathname is a symbolic link, and the link and object that the link points to have different owners. from = part When checking symbolic links (parameters on and if_not_owner ), all components of the pathname are normally checked. Checking of symbolic links in the initial part of the pathname may be avoided by specifying additionally the from = part parameter. In this case, symbolic links are checked only from the pathname component that follows the specified initial part. If the value is not an initial part of the pathname checked, the whole pathname is checked as if this parameter was not specified at all. If the value matches the whole file name, symbolic links are not checked. The parameter value can contain variables.

This directive is only available on systems that have the openat() and fstatat() interfaces. Such systems include modern versions of FreeBSD, Linux, and Solaris.

Parameters on and if_not_owner add a processing overhead.

On systems that do not support opening of directories only for search, to use these parameters it is required that worker processes have read permissions for all directories being checked.

Syntax: error_page code . [ = [ response ]] uri ;
Default:
Context: http , server , location , if in location

Defines the URI that will be shown for the specified errors. A uri value can contain variables.

This causes an internal redirect to the specified uri with the client request method changed to “ GET ” (for all methods other than “ GET ” and “ HEAD ”).

Furthermore, it is possible to change the response code to another using the “ = response ” syntax, for example:

If an error response is processed by a proxied server or a FastCGI/uwsgi/SCGI/gRPC server, and the server may return different response codes (e.g., 200, 302, 401 or 404), it is possible to respond with the code it returns:

If there is no need to change URI and method during internal redirection it is possible to pass error processing into a named location:

If uri processing leads to an error, the status code of the last occurred error is returned to the client.

It is also possible to use URL redirects for error processing:

In this case, by default, the response code 302 is returned to the client. It can only be changed to one of the redirect status codes (301, 302, 303, 307, and 308).

The code 307 was not treated as a redirect until versions 1.1.16 and 1.0.13.

The code 308 was not treated as a redirect until version 1.13.0.

These directives are inherited from the previous configuration level if and only if there are no error_page directives defined on the current level.

Syntax: etag on | off ;
Default:
Context: http , server , location

This directive appeared in version 1.3.3.

Enables or disables automatic generation of the “ETag” response header field for static resources.

Syntax: http < . >
Default:
Context: main

Provides the configuration file context in which the HTTP server directives are specified.

Syntax: if_modified_since off | exact | before ;
Default:
Context: http , server , location

This directive appeared in version 0.7.24.

Specifies how to compare modification time of a response with the time in the “If-Modified-Since” request header field:

off the response is always considered modified (0.7.34); exact exact match; before modification time of the response is less than or equal to the time in the “If-Modified-Since” request header field.

Syntax: ignore_invalid_headers on | off ;
Default:
Context: http , server

Controls whether header fields with invalid names should be ignored. Valid names are composed of English letters, digits, hyphens, and possibly underscores (as controlled by the underscores_in_headers directive).

If the directive is specified on the server level, the value from the default server can be used. Details are provided in the “Virtual server selection” section.

Syntax: internal;
Default:
Context: location

Specifies that a given location can only be used for internal requests. For external requests, the client error 404 (Not Found) is returned. Internal requests are the following:

  • requests redirected by the error_page, index, random_index, and try_files directives;
  • requests redirected by the “X-Accel-Redirect” response header field from an upstream server;
  • subrequests formed by the “ include virtual ” command of the ngx_http_ssi_module module, by the ngx_http_addition_module module directives, and by auth_request and mirror directives;
  • requests changed by the rewrite directive.

There is a limit of 10 internal redirects per request to prevent request processing cycles that can occur in incorrect configurations. If this limit is reached, the error 500 (Internal Server Error) is returned. In such cases, the “rewrite or internal redirection cycle” message can be seen in the error log.

Syntax: keepalive_disable none | browser . ;
Default:
Context: http , server , location

Disables keep-alive connections with misbehaving browsers. The browser parameters specify which browsers will be affected. The value msie6 disables keep-alive connections with old versions of MSIE, once a POST request is received. The value safari disables keep-alive connections with Safari and Safari-like browsers on macOS and macOS-like operating systems. The value none enables keep-alive connections with all browsers.

Prior to version 1.1.18, the value safari matched all Safari and Safari-like browsers on all operating systems, and keep-alive connections with them were disabled by default.

Syntax: keepalive_requests number ;
Default:
Context: http , server , location

This directive appeared in version 0.8.0.

Sets the maximum number of requests that can be served through one keep-alive connection. After the maximum number of requests are made, the connection is closed.

Closing connections periodically is necessary to free per-connection memory allocations. Therefore, using too high maximum number of requests could result in excessive memory usage and not recommended.

Prior to version 1.19.10, the default value was 100.

Syntax: keepalive_time time ;
Default:
Context: http , server , location

This directive appeared in version 1.19.10.

Limits the maximum time during which requests can be processed through one keep-alive connection. After this time is reached, the connection is closed following the subsequent request processing.

Syntax: keepalive_timeout timeout [ header_timeout ];
Default:
Context: http , server , location

The first parameter sets a timeout during which a keep-alive client connection will stay open on the server side. The zero value disables keep-alive client connections. The optional second parameter sets a value in the “Keep-Alive: timeout= time ” response header field. Two parameters may differ.

The “Keep-Alive: timeout= time ” header field is recognized by Mozilla and Konqueror. MSIE closes keep-alive connections by itself in about 60 seconds.

Syntax: large_client_header_buffers number size ;
Default:
Context: http , server

Sets the maximum number and size of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.

If the directive is specified on the server level, the value from the default server can be used. Details are provided in the “Virtual server selection” section.

Syntax: limit_except method . < . >
Default:
Context: location

Limits allowed HTTP methods inside a location. The method parameter can be one of the following: GET , HEAD , POST , PUT , DELETE , MKCOL , COPY , MOVE , OPTIONS , PROPFIND , PROPPATCH , LOCK , UNLOCK , or PATCH . Allowing the GET method makes the HEAD method also allowed. Access to other methods can be limited using the ngx_http_access_module, ngx_http_auth_basic_module, and ngx_http_auth_jwt_module (1.13.10) modules directives:

Please note that this will limit access to all methods except GET and HEAD.

Syntax: limit_rate rate ;
Default:
Context: http , server , location , if in location

Limits the rate of response transmission to a client. The rate is specified in bytes per second. The zero value disables rate limiting. The limit is set per a request, and so if a client simultaneously opens two connections, the overall rate will be twice as much as the specified limit.

Parameter value can contain variables (1.17.0). It may be useful in cases where rate should be limited depending on a certain condition:

Rate limit can also be set in the $limit_rate variable, however, since version 1.17.0, this method is not recommended:

Rate limit can also be set in the “X-Accel-Limit-Rate” header field of a proxied server response. This capability can be disabled using the proxy_ignore_headers, fastcgi_ignore_headers, uwsgi_ignore_headers, and scgi_ignore_headers directives.

Syntax: limit_rate_after size ;
Default:
Context: http , server , location , if in location

This directive appeared in version 0.8.0.

Sets the initial amount after which the further transmission of a response to a client will be rate limited. Parameter value can contain variables (1.17.0).

Syntax: lingering_close off | on | always ;
Default:
Context: http , server , location

This directive appeared in versions 1.1.0 and 1.0.6.

Controls how nginx closes client connections.

The default value “ on ” instructs nginx to wait for and process additional data from a client before fully closing a connection, but only if heuristics suggests that a client may be sending more data.

The value “ always ” will cause nginx to unconditionally wait for and process additional client data.

The value “ off ” tells nginx to never wait for more data and close the connection immediately. This behavior breaks the protocol and should not be used under normal circumstances.

To control closing HTTP/2 connections, the directive must be specified on the server level (1.19.1).

Syntax: lingering_time time ;
Default:
Context: http , server , location

When lingering_close is in effect, this directive specifies the maximum time during which nginx will process (read and ignore) additional data coming from a client. After that, the connection will be closed, even if there will be more data.

Syntax: lingering_timeout time ;
Default:
Context: http , server , location

When lingering_close is in effect, this directive specifies the maximum waiting time for more client data to arrive. If data are not received during this time, the connection is closed. Otherwise, the data are read and ignored, and nginx starts waiting for more data again. The “wait-read-ignore” cycle is repeated, but no longer than specified by the lingering_time directive.

Syntax: listen address [: port ] [ default_server ] [ ssl ] [ http2 | spdy ] [ proxy_protocol ] [ setfib = number ] [ fastopen = number ] [ backlog = number ] [ rcvbuf = size ] [ sndbuf = size ] [ accept_filter = filter ] [ deferred ] [ bind ] [ ipv6only = on | off ] [ reuseport ] [ so_keepalive = on | off |[ keepidle ]:[ keepintvl ]:[ keepcnt ]];
listen port [ default_server ] [ ssl ] [ http2 | spdy ] [ proxy_protocol ] [ setfib = number ] [ fastopen = number ] [ backlog = number ] [ rcvbuf = size ] [ sndbuf = size ] [ accept_filter = filter ] [ deferred ] [ bind ] [ ipv6only = on | off ] [ reuseport ] [ so_keepalive = on | off |[ keepidle ]:[ keepintvl ]:[ keepcnt ]];
listen unix: path [ default_server ] [ ssl ] [ http2 | spdy ] [ proxy_protocol ] [ backlog = number ] [ rcvbuf = size ] [ sndbuf = size ] [ accept_filter = filter ] [ deferred ] [ bind ] [ so_keepalive = on | off |[ keepidle ]:[ keepintvl ]:[ keepcnt ]];
Default:
Context: server

Sets the address and port for IP, or the path for a UNIX-domain socket on which the server will accept requests. Both address and port , or only address or only port can be specified. An address may also be a hostname, for example:

IPv6 addresses (0.7.36) are specified in square brackets:

UNIX-domain sockets (0.8.21) are specified with the “ unix: ” prefix:

If only address is given, the port 80 is used.

If the directive is not present then either *:80 is used if nginx runs with the superuser privileges, or *:8000 otherwise.

The default_server parameter, if present, will cause the server to become the default server for the specified address : port pair. If none of the directives have the default_server parameter then the first server with the address : port pair will be the default server for this pair.

In versions prior to 0.8.21 this parameter is named simply default .

The ssl parameter (0.7.14) allows specifying that all connections accepted on this port should work in SSL mode. This allows for a more compact configuration for the server that handles both HTTP and HTTPS requests.

The http2 parameter (1.9.5) configures the port to accept HTTP/2 connections. Normally, for this to work the ssl parameter should be specified as well, but nginx can also be configured to accept HTTP/2 connections without SSL.

The spdy parameter (1.3.15-1.9.4) allows accepting SPDY connections on this port. Normally, for this to work the ssl parameter should be specified as well, but nginx can also be configured to accept SPDY connections without SSL.

The proxy_protocol parameter (1.5.12) allows specifying that all connections accepted on this port should use the PROXY protocol.

The PROXY protocol version 2 is supported since version 1.13.11.

The listen directive can have several additional parameters specific to socket-related system calls. These parameters can be specified in any listen directive, but only once for a given address : port pair.

In versions prior to 0.8.21, they could only be specified in the listen directive together with the default parameter.

setfib = number this parameter (0.8.44) sets the associated routing table, FIB (the SO_SETFIB option) for the listening socket. This currently works only on FreeBSD. fastopen = number enables “TCP Fast Open” for the listening socket (1.5.8) and limits the maximum length for the queue of connections that have not yet completed the three-way handshake.

Do not enable this feature unless the server can handle receiving the same SYN packet with data more than once.

Prior to version 1.3.4, if this parameter was omitted then the operating system’s settings were in effect for the socket.

Inappropriate use of this option may have its security implications.

Syntax: location [ = |

] uri < . >
location @ name < . > Default: — Context: server , location

Sets configuration depending on a request URI.

The matching is performed against a normalized URI, after decoding the text encoded in the “ %XX ” form, resolving references to relative path components “ . ” and “ .. ”, and possible compression of two or more adjacent slashes into a single slash.

A location can either be defined by a prefix string, or by a regular expression. Regular expressions are specified with the preceding “

* ” modifier (for case-insensitive matching), or the “

” modifier (for case-sensitive matching). To find location matching a given request, nginx first checks locations defined using the prefix strings (prefix locations). Among them, the location with the longest matching prefix is selected and remembered. Then regular expressions are checked, in the order of their appearance in the configuration file. The search of regular expressions terminates on the first match, and the corresponding configuration is used. If no match with a regular expression is found then the configuration of the prefix location remembered earlier is used.

location blocks can be nested, with some exceptions mentioned below.

For case-insensitive operating systems such as macOS and Cygwin, matching with prefix strings ignores a case (0.7.7). However, comparison is limited to one-byte locales.

Regular expressions can contain captures (0.7.40) that can later be used in other directives.

If the longest matching prefix location has the “ ^

” modifier then regular expressions are not checked.

Also, using the “ = ” modifier it is possible to define an exact match of URI and location. If an exact match is found, the search terminates. For example, if a “ / ” request happens frequently, defining “ location = / ” will speed up the processing of these requests, as search terminates right after the first comparison. Such a location cannot obviously contain nested locations.

In versions from 0.7.1 to 0.8.41, if a request matched the prefix location without the “ = ” and “ ^

” modifiers, the search also terminated and regular expressions were not checked.

Let’s illustrate the above by an example:

The “ / ” request will match configuration A, the “ /index.html ” request will match configuration B, the “ /documents/document.html ” request will match configuration C, the “ /images/1.gif ” request will match configuration D, and the “ /documents/1.jpg ” request will match configuration E.

The “ @ ” prefix defines a named location. Such a location is not used for a regular request processing, but instead used for request redirection. They cannot be nested, and cannot contain nested locations.

If a location is defined by a prefix string that ends with the slash character, and requests are processed by one of proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, memcached_pass, or grpc_pass, then the special processing is performed. In response to a request with URI equal to this string, but without the trailing slash, a permanent redirect with the code 301 will be returned to the requested URI with the slash appended. If this is not desired, an exact match of the URI and location could be defined like this:

Syntax: log_not_found on | off ;
Default:
Context: http , server , location

Enables or disables logging of errors about not found files into error_log.

Syntax: log_subrequest on | off ;
Default:
Context: http , server , location

Enables or disables logging of subrequests into access_log.

Syntax: max_ranges number ;
Default:
Context: http , server , location

This directive appeared in version 1.1.2.

Limits the maximum allowed number of ranges in byte-range requests. Requests that exceed the limit are processed as if there were no byte ranges specified. By default, the number of ranges is not limited. The zero value disables the byte-range support completely.

Syntax: merge_slashes on | off ;
Default:
Context: http , server

Enables or disables compression of two or more adjacent slashes in a URI into a single slash.

Note that compression is essential for the correct matching of prefix string and regular expression locations. Without it, the “ //scripts/one.php ” request would not match

and might be processed as a static file. So it gets converted to “ /scripts/one.php ”.

Turning the compression off can become necessary if a URI contains base64-encoded names, since base64 uses the “ / ” character internally. However, for security considerations, it is better to avoid turning the compression off.

If the directive is specified on the server level, the value from the default server can be used. Details are provided in the “Virtual server selection” section.

Syntax: msie_padding on | off ;
Default:
Context: http , server , location

Enables or disables adding comments to responses for MSIE clients with status greater than 400 to increase the response size to 512 bytes.

Syntax: msie_refresh on | off ;
Default:
Context: http , server , location

Enables or disables issuing refreshes instead of redirects for MSIE clients.

Syntax: open_file_cache off ;
open_file_cache max = N [ inactive = time ];
Default:
Context: http , server , location

Configures a cache that can store:

  • open file descriptors, their sizes and modification times;
  • information on existence of directories;
  • file lookup errors, such as “file not found”, “no read permission”, and so on.

Caching of errors should be enabled separately by the open_file_cache_errors directive.

The directive has the following parameters:

max sets the maximum number of elements in the cache; on cache overflow the least recently used (LRU) elements are removed; inactive defines a time after which an element is removed from the cache if it has not been accessed during this time; by default, it is 60 seconds; off disables the cache.

Syntax: open_file_cache_errors on | off ;
Default:
Context: http , server , location

Enables or disables caching of file lookup errors by open_file_cache.

Syntax: open_file_cache_min_uses number ;
Default:
Context: http , server , location

Sets the minimum number of file accesses during the period configured by the inactive parameter of the open_file_cache directive, required for a file descriptor to remain open in the cache.

Syntax: open_file_cache_valid time ;
Default:
Context: http , server , location

Sets a time after which open_file_cache elements should be validated.

Syntax: output_buffers number size ;
Default:
Context: http , server , location

Sets the number and size of the buffers used for reading a response from a disk.

Prior to version 1.9.5, the default value was 1 32k.

Syntax: port_in_redirect on | off ;
Default:
Context: http , server , location

Enables or disables specifying the port in absolute redirects issued by nginx.

The use of the primary server name in redirects is controlled by the server_name_in_redirect directive.

Syntax: postpone_output size ;
Default:
Context: http , server , location

If possible, the transmission of client data will be postponed until nginx has at least size bytes of data to send. The zero value disables postponing data transmission.

Syntax: read_ahead size ;
Default:
Context: http , server , location

Sets the amount of pre-reading for the kernel when working with file.

On Linux, the posix_fadvise(0, 0, 0, POSIX_FADV_SEQUENTIAL) system call is used, and so the size parameter is ignored.

On FreeBSD, the fcntl(O_READAHEAD, size ) system call, supported since FreeBSD 9.0-CURRENT, is used. FreeBSD 7 has to be patched.

Syntax: recursive_error_pages on | off ;
Default:
Context: http , server , location

Enables or disables doing several redirects using the error_page directive. The number of such redirects is limited.

Syntax: request_pool_size size ;
Default:
Context: http , server

Allows accurate tuning of per-request memory allocations. This directive has minimal impact on performance and should not generally be used.

Syntax: reset_timedout_connection on | off ;
Default:
Context: http , server , location

Enables or disables resetting timed out connections and connections closed with the non-standard code 444 (1.15.2). The reset is performed as follows. Before closing a socket, the SO_LINGER option is set on it with a timeout value of 0. When the socket is closed, TCP RST is sent to the client, and all memory occupied by this socket is released. This helps avoid keeping an already closed socket with filled buffers in a FIN_WAIT1 state for a long time.

It should be noted that timed out keep-alive connections are closed normally.

Syntax: resolver address . [ valid = time ] [ ipv4 = on | off ] [ ipv6 = on | off ] [ status_zone = zone ];
Default:
Context: http , server , location

Configures name servers used to resolve names of upstream servers into addresses, for example:

The address can be specified as a domain name or IP address, with an optional port (1.3.1, 1.2.2). If port is not specified, the port 53 is used. Name servers are queried in a round-robin fashion.

Before version 1.1.7, only a single name server could be configured. Specifying name servers using IPv6 addresses is supported starting from versions 1.3.1 and 1.2.2.

By default, nginx will look up both IPv4 and IPv6 addresses while resolving. If looking up of IPv4 or IPv6 addresses is not desired, the ipv4=off (1.23.1) or the ipv6=off parameter can be specified.

Resolving of names into IPv6 addresses is supported starting from version 1.5.8.

By default, nginx caches answers using the TTL value of a response. An optional valid parameter allows overriding it:

Before version 1.1.9, tuning of caching time was not possible, and nginx always cached answers for the duration of 5 minutes.

To prevent DNS spoofing, it is recommended configuring DNS servers in a properly secured trusted local network.

The optional status_zone parameter (1.17.1) enables collection of DNS server statistics of requests and responses in the specified zone . The parameter is available as part of our commercial subscription.

Syntax: resolver_timeout time ;
Default:
Context: http , server , location

Sets a timeout for name resolution, for example:

Syntax: root path ;
Default:
Context: http , server , location , if in location

Sets the root directory for requests. For example, with the following configuration

The /data/w3/i/top.gif file will be sent in response to the “ /i/top.gif ” request.

The path value can contain variables, except $document_root and $realpath_root .

A path to the file is constructed by merely adding a URI to the value of the root directive. If a URI has to be modified, the alias directive should be used.

Syntax: satisfy all | any ;
Default:
Context: http , server , location
Syntax: send_lowat size ;
Default:
Context: http , server , location

If the directive is set to a non-zero value, nginx will try to minimize the number of send operations on client sockets by using either NOTE_LOWAT flag of the kqueue method or the SO_SNDLOWAT socket option. In both cases the specified size is used.

This directive is ignored on Linux, Solaris, and Windows.

Syntax: send_timeout time ;
Default:
Context: http , server , location

Sets a timeout for transmitting a response to the client. The timeout is set only between two successive write operations, not for the transmission of the whole response. If the client does not receive anything within this time, the connection is closed.

Syntax: sendfile on | off ;
Default:
Context: http , server , location , if in location

Enables or disables the use of sendfile() .

Starting from nginx 0.8.12 and FreeBSD 5.2.1, aio can be used to pre-load data for sendfile() :

In this configuration, sendfile() is called with the SF_NODISKIO flag which causes it not to block on disk I/O, but, instead, report back that the data are not in memory. nginx then initiates an asynchronous data load by reading one byte. On the first read, the FreeBSD kernel loads the first 128K bytes of a file into memory, although next reads will only load data in 16K chunks. This can be changed using the read_ahead directive.

Before version 1.7.11, pre-loading could be enabled with aio sendfile; .

Syntax: sendfile_max_chunk size ;
Default:
Context: http , server , location

Limits the amount of data that can be transferred in a single sendfile() call. Without the limit, one fast connection may seize the worker process entirely.

Prior to version 1.21.4, by default there was no limit.

Syntax: server < . >
Default:
Context: http

Sets configuration for a virtual server. There is no clear separation between IP-based (based on the IP address) and name-based (based on the “Host” request header field) virtual servers. Instead, the listen directives describe all addresses and ports that should accept connections for the server, and the server_name directive lists all server names. Example configurations are provided in the “How nginx processes a request” document.

Syntax: server_name name . ;
Default:
Context: server

Sets names of a virtual server, for example:

The first name becomes the primary server name.

Server names can include an asterisk (“ * ”) replacing the first or last part of a name:

Such names are called wildcard names.

The first two of the names mentioned above can be combined in one:

It is also possible to use regular expressions in server names, preceding the name with a tilde (“

Regular expressions can contain captures (0.7.40) that can later be used in other directives:

Named captures in regular expressions create variables (0.8.25) that can later be used in other directives:

If the directive’s parameter is set to “ $hostname ” (0.9.4), the machine’s hostname is inserted.

It is also possible to specify an empty server name (0.7.11):

It allows this server to process requests without the “Host” header field — instead of the default server — for the given address:port pair. This is the default setting.

Before 0.8.48, the machine’s hostname was used by default.

During searching for a virtual server by name, if the name matches more than one of the specified variants, (e.g. both a wildcard name and regular expression match), the first matching variant will be chosen, in the following order of priority:

  1. the exact name
  2. the longest wildcard name starting with an asterisk, e.g. “ *.example.com ”
  3. the longest wildcard name ending with an asterisk, e.g. “ mail.* ”
  4. the first matching regular expression (in order of appearance in the configuration file)

Detailed description of server names is provided in a separate Server names document.

Syntax: server_name_in_redirect on | off ;
Default:
Context: http , server , location

Enables or disables the use of the primary server name, specified by the server_name directive, in absolute redirects issued by nginx. When the use of the primary server name is disabled, the name from the “Host” request header field is used. If this field is not present, the IP address of the server is used.

The use of a port in redirects is controlled by the port_in_redirect directive.

Syntax: server_names_hash_bucket_size size ;
Default:
Context: http

Sets the bucket size for the server names hash tables. The default value depends on the size of the processor’s cache line. The details of setting up hash tables are provided in a separate document.

Syntax: server_names_hash_max_size size ;
Default:
Context: http

Sets the maximum size of the server names hash tables. The details of setting up hash tables are provided in a separate document.

Syntax: server_tokens on | off | build | string ;
Default:
Context: http , server , location

Enables or disables emitting nginx version on error pages and in the “Server” response header field.

The build parameter (1.11.10) enables emitting a build name along with nginx version.

Additionally, as part of our commercial subscription, starting from version 1.9.13 the signature on error pages and the “Server” response header field value can be set explicitly using the string with variables. An empty string disables the emission of the “Server” field.

Syntax: subrequest_output_buffer_size size ;
Default:
Context: http , server , location

This directive appeared in version 1.13.10.

Sets the size of the buffer used for storing the response body of a subrequest. By default, the buffer size is equal to one memory page. This is either 4K or 8K, depending on a platform. It can be made smaller, however.

The directive is applicable only for subrequests with response bodies saved into memory. For example, such subrequests are created by SSI.

Syntax: tcp_nodelay on | off ;
Default:
Context: http , server , location

Enables or disables the use of the TCP_NODELAY option. The option is enabled when a connection is transitioned into the keep-alive state. Additionally, it is enabled on SSL connections, for unbuffered proxying, and for WebSocket proxying.

Syntax: tcp_nopush on | off ;
Default:
Context: http , server , location

Enables or disables the use of the TCP_NOPUSH socket option on FreeBSD or the TCP_CORK socket option on Linux. The options are enabled only when sendfile is used. Enabling the option allows

  • sending the response header and the beginning of a file in one packet, on Linux and FreeBSD 4.*;
  • sending a file in full packets.
Syntax: try_files file . uri ;
try_files file . = code ;
Default:
Context: server , location

Checks the existence of files in the specified order and uses the first found file for request processing; the processing is performed in the current context. The path to a file is constructed from the file parameter according to the root and alias directives. It is possible to check directory’s existence by specifying a slash at the end of a name, e.g. “ $uri/ ”. If none of the files were found, an internal redirect to the uri specified in the last parameter is made. For example:

The last parameter can also point to a named location, as shown in examples below. Starting from version 0.7.51, the last parameter can also be a code :

Example in proxying Mongrel:

Example for Drupal/FastCGI:

In the following example,

the try_files directive is equivalent to

try_files checks the existence of the PHP file before passing the request to the FastCGI server.

Example for WordPress and Joomla:

Syntax: types < . >
Default:
Context: http , server , location

Maps file name extensions to MIME types of responses. Extensions are case-insensitive. Several extensions can be mapped to one type, for example:

A sufficiently full mapping table is distributed with nginx in the conf/mime.types file.

To make a particular location emit the “ application/octet-stream ” MIME type for all requests, the following configuration can be used:

Syntax: types_hash_bucket_size size ;
Default:
Context: http , server , location

Sets the bucket size for the types hash tables. The details of setting up hash tables are provided in a separate document.

Prior to version 1.5.13, the default value depended on the size of the processor’s cache line.

Syntax: types_hash_max_size size ;
Default:
Context: http , server , location

Sets the maximum size of the types hash tables. The details of setting up hash tables are provided in a separate document.

Syntax: underscores_in_headers on | off ;
Default:
Context: http , server

Enables or disables the use of underscores in client request header fields. When the use of underscores is disabled, request header fields whose names contain underscores are marked as invalid and become subject to the ignore_invalid_headers directive.

If the directive is specified on the server level, the value from the default server can be used. Details are provided in the “Virtual server selection” section.

Syntax: variables_hash_bucket_size size ;
Default:
Context: http

Sets the bucket size for the variables hash table. The details of setting up hash tables are provided in a separate document.

Syntax: variables_hash_max_size size ;
Default:
Context: http

Sets the maximum size of the variables hash table. The details of setting up hash tables are provided in a separate document.

Prior to version 1.5.13, the default value was 512.

Embedded Variables

The ngx_http_core_module module supports embedded variables with names matching the Apache Server variables. First of all, these are variables representing client request header fields, such as $http_user_agent , $http_cookie , and so on. Also there are other variables:

$arg_ name argument name in the request line $args arguments in the request line $binary_remote_addr client address in a binary form, value’s length is always 4 bytes for IPv4 addresses or 16 bytes for IPv6 addresses $body_bytes_sent number of bytes sent to a client, not counting the response header; this variable is compatible with the “ %B ” parameter of the mod_log_config Apache module $bytes_sent number of bytes sent to a client (1.3.8, 1.2.5) $connection connection serial number (1.3.8, 1.2.5) $connection_requests current number of requests made through a connection (1.3.8, 1.2.5) $connection_time connection time in seconds with a milliseconds resolution (1.19.10) $content_length “Content-Length” request header field $content_type “Content-Type” request header field $cookie_ name the name cookie $document_root root or alias directive’s value for the current request $document_uri same as $uri $host in this order of precedence: host name from the request line, or host name from the “Host” request header field, or the server name matching a request $hostname host name $http_ name arbitrary request header field; the last part of a variable name is the field name converted to lower case with dashes replaced by underscores $https “ on ” if connection operates in SSL mode, or an empty string otherwise $is_args “ ? ” if a request line has arguments, or an empty string otherwise $limit_rate setting this variable enables response rate limiting; see limit_rate $msec current time in seconds with the milliseconds resolution (1.3.9, 1.2.6) $nginx_version nginx version $pid PID of the worker process $pipe “ p ” if request was pipelined, “ . ” otherwise (1.3.12, 1.2.7) $proxy_protocol_addr client address from the PROXY protocol header (1.5.12)

The PROXY protocol must be previously enabled by setting the proxy_protocol parameter in the listen directive.

$proxy_protocol_port client port from the PROXY protocol header (1.11.0)

The PROXY protocol must be previously enabled by setting the proxy_protocol parameter in the listen directive.

$proxy_protocol_server_addr server address from the PROXY protocol header (1.17.6)

The PROXY protocol must be previously enabled by setting the proxy_protocol parameter in the listen directive.

$proxy_protocol_server_port server port from the PROXY protocol header (1.17.6)

The PROXY protocol must be previously enabled by setting the proxy_protocol parameter in the listen directive.

$proxy_protocol_tlv_ name TLV from the PROXY Protocol header (1.23.2). The name can be a TLV type name or its numeric value. In the latter case, the value is hexadecimal and should be prefixed with 0x :

The following TLV type names are supported:

  • alpn ( 0x01 ) — upper layer protocol used over the connection
  • authority ( 0x02 ) — host name value passed by the client
  • unique_id ( 0x05 ) — unique connection id
  • netns ( 0x30 ) — name of the namespace
  • ssl ( 0x20 ) — binary SSL TLV structure

The following SSL TLV type names are supported:

  • ssl_version ( 0x21 ) — SSL version used in client connection
  • ssl_cn ( 0x22 ) — SSL certificate Common Name
  • ssl_cipher ( 0x23 ) — name of the used cipher
  • ssl_sig_alg ( 0x24 ) — algorithm used to sign the certificate
  • ssl_key_alg ( 0x25 ) — public-key algorithm

Also, the following special SSL TLV type name is supported:

  • ssl_verify — client SSL certificate verification result, 0 if the client presented a certificate and it was successfully verified, non-zero otherwise.

The PROXY protocol must be previously enabled by setting the proxy_protocol parameter in the listen directive.

$query_string same as $args $realpath_root an absolute pathname corresponding to the root or alias directive’s value for the current request, with all symbolic links resolved to real paths $remote_addr client address $remote_port client port $remote_user user name supplied with the Basic authentication $request full original request line $request_body request body

The variable’s value is made available in locations processed by the proxy_pass, fastcgi_pass, uwsgi_pass, and scgi_pass directives when the request body was read to a memory buffer.

$request_body_file name of a temporary file with the request body

At the end of processing, the file needs to be removed. To always write the request body to a file, client_body_in_file_only needs to be enabled. When the name of a temporary file is passed in a proxied request or in a request to a FastCGI/uwsgi/SCGI server, passing the request body should be disabled by the proxy_pass_request_body off, fastcgi_pass_request_body off, uwsgi_pass_request_body off, or scgi_pass_request_body off directives, respectively.

$request_completion “ OK ” if a request has completed, or an empty string otherwise $request_filename file path for the current request, based on the root or alias directives, and the request URI $request_id unique request identifier generated from 16 random bytes, in hexadecimal (1.11.0) $request_length request length (including request line, header, and request body) (1.3.12, 1.2.7) $request_method request method, usually “ GET ” or “ POST ” $request_time request processing time in seconds with a milliseconds resolution (1.3.9, 1.2.6); time elapsed since the first bytes were read from the client $request_uri full original request URI (with arguments) $scheme request scheme, “ http ” or “ https ” $sent_http_ name arbitrary response header field; the last part of a variable name is the field name converted to lower case with dashes replaced by underscores $sent_trailer_ name arbitrary field sent at the end of the response (1.13.2); the last part of a variable name is the field name converted to lower case with dashes replaced by underscores $server_addr an address of the server which accepted a request

Computing a value of this variable usually requires one system call. To avoid a system call, the listen directives must specify addresses and use the bind parameter.

$server_name name of the server which accepted a request $server_port port of the server which accepted a request $server_protocol request protocol, usually “ HTTP/1.0 ”, “ HTTP/1.1 ”, or “HTTP/2.0” $status response status (1.3.2, 1.2.2) $tcpinfo_rtt , $tcpinfo_rttvar , $tcpinfo_snd_cwnd , $tcpinfo_rcv_space information about the client TCP connection; available on systems that support the TCP_INFO socket option $time_iso8601 local time in the ISO 8601 standard format (1.3.12, 1.2.7) $time_local local time in the Common Log Format (1.3.12, 1.2.7) $uri current URI in request, normalized

Источник

error_page

Syntax: error_page code … [=[response]] uri;
Default: —
Context: http, server, location, if in location

Defines the URI that will be shown for the specified errors. A uri value can contain variables.

Example:

error_page 404             /404.html;
error_page 500 502 503 504 /50x.html;

This causes an internal redirect to the specified uri with the client request method changed to “GET” (for all methods other than “GET” and “HEAD”).

Furthermore, it is possible to change the response code to another using the “=response” syntax, for example:

error_page 404 =200 /empty.gif;

If an error response is processed by a proxied server or a FastCGI/uwsgi/SCGI/gRPC server, and the server may return different response codes (e.g., 200, 302, 401 or 404), it is possible to respond with the code it returns:

error_page 404 = /404.php;

If there is no need to change URI and method during internal redirection it is possible to pass error processing into a named location:

location / {
    error_page 404 = @fallback;
}

location @fallback {
    proxy_pass http://backend;
}

If uri processing leads to an error, the status code of the last occurred error is returned to the client.
It is also possible to use URL redirects for error processing:

error_page 403      http://example.com/forbidden.html;
error_page 404 =301 http://example.com/notfound.html;

In this case, by default, the response code 302 is returned to the client. It can only be changed to one of the redirect status codes (301, 302, 303, 307, and 308).

The code 307 was not treated as a redirect until versions 1.1.16 and 1.0.13.
The code 308 was not treated as a redirect until version 1.13.0.

These directives are inherited from the previous configuration level if and only if there are no error_page directives defined on the current level.

Matching a Homepage

I have been doing a lot of experimenting with my website lately. Recently, I was trying to configure some special rules for my website’s homepage.
In Nginx, I wanted to match requests for the homepage only. When I looked in the access log, requests for https://www.tollmanz.com are registered as /. The excerpted headers for the request looks like:

authority: www.tollmanz.com
method: GET
path: /
scheme: https

Given that the path for the homepage is simply /, I added the location to my configuration. A heavily excerpted configuration looked something like:

server {
    listen         443 ssl;
    server_name    www.tollmanz.com;
    root           /path/to/tollmanz.com/;

    # Match homepage
    location = / {}

    # Match assets
    location ~* .(?:ico|css|js|gif|jpe?g|png|woff2|woff|ttf)$ {}

    # All other files
    location / {}
}

I set up three locations: homepage, assets, and all other files. Nginx docs are very clear that location = / {} would match / over location / {} because it is more specific and should therefore take precedence; however, that absolutely did not work with any amount of trying.

After a ton of searching, I finally stumbled upon the index directive docs. In an aside at the end of the page, it mentions:

It should be noted that using an index file causes an internal redirect,
and the request can be processed in a different location…
a “/” request will actually be processed in the second location as “/index.html”.

By default, the index directive is set to display the index.html file. Since my site is a Jekyll site, all of the pages are index.html files within a specific directory. When I thought I needed to match /, I actually needed to match /index.html. Since Nginx by default will look for an index.html file inside of a directory request, I had to update my location to specifically match /index.html, even though the logs only suggest that I’m trying to match /. I needed to update my config to:

server {
    listen         443 ssl;
    server_name    www.tollmanz.com;
    root           /path/to/tollmanz.com/;

    # Match homepage
    location = /index.html {}

    # Match assets
    location ~* .(?:ico|css|js|gif|jpe?g|png|woff2|woff|ttf)$ {}

    # All other files
    location / {}
}

This configuration makes a lot of sense in the end, but it was terribly confusing to work out. I really hope this note-to-self saves someone time in the future.

index

Syntax: index file …;
Default: index index.html;
Context: http, server, location

Defines files that will be used as an index.
The file name can contain variables.
Files are checked in the specified order.
The last element of the list can be a file with an absolute path.

Example:

index index.$geo.html index.0.html /index.html;

It should be noted that using an index file causes an internal redirect, and the request can be processed in a different location.
For example, with the following configuration:

location = / {    
    index index.html;    
}    
 
location / {    
    ...    
}    

a “/” request will actually be processed in the second location as “/index.html”.

internal

Syntax: internal;
Default: —
Context: location

Specifies that a given location can only be used for internal requests.

For external requests, the client error 404 (Not Found) is returned,
i.e. an internal settings in the nginx configuration means that any request with that uri from the external source will be served with 404. It has to come only from the internal.

Internal requests are the following:

  • requests redirected by the error_page, index, random_index, and try_files directives;
  • requests redirected by the “X-Accel-Redirect” response header field from an upstream server;
  • subrequests formed by the “include virtual” command of the ngx_http_ssi_module module, by the ngx_http_addition_module module directives, and by auth_request and mirror directives;
  • requests changed by the rewrite directive.

Example:

error_page 404 /404.html;
   
location = /404.html {
    internal;
}

There is a limit of 10 internal redirects per request to prevent request processing cycles that can occur in incorrect configurations. If this limit is reached, the error 500 (Internal Server Error) is returned. In such cases, the “rewrite or internal redirection cycle” message can be seen in the error log.

Configuring Locations

NGINX Plus can send traffic to different proxies or serve different files based on the request URIs. These blocks are defined using the location directive placed within a server directive.

For example, you can define three location blocks to instruct the virtual server to send some requests to one proxied server, send other requests to a different proxied server, and serve the rest of the requests by delivering files from the local file system.

NGINX Plus tests request URIs against the parameters of all location directives and applies the directives defined in the matching location. Inside each location block, it is usually possible (with a few exceptions) to place even more location directives to further refine the processing for specific groups of requests.

Note: In this guide, the word location refers to a single location context.

There are two types of parameter to the location directive: prefix strings (pathnames) and regular expressions. For a request URI to match a prefix string, it must start with the prefix string.

The following sample location with a pathname parameter matches request URIs that begin with /some/path/, such as /some/path/document.html. (It does not match /my-site/some/path because /some/path does not occur at the start of that URI.)

location /some/path/ {
    #...
}

A regular expression is preceded with the tilde (~) for case-sensitive matching, or the tilde-asterisk (~*) for case-insensitive matching. The following example matches URIs that include the string .html or .htm in any position.

location ~ .html? {
    #...
}

NGINX Location Priority

To find the location that best matches a URI, NGINX Plus first compares the URI to the locations with a prefix string. It then searches the locations with a regular expression.

Higher priority is given to regular expressions, unless the ^~ modifier is used. Among the prefix strings NGINX Plus selects the most specific one (that is, the longest and most complete string). The exact logic for selecting a location to process a request is given below:

Test the URI against all prefix strings.
The = (equals sign) modifier defines an exact match of the URI and a prefix string. If the exact match is found, the search stops.
If the ^~ (caret-tilde) modifier prepends the longest matching prefix string, the regular expressions are not checked.
Store the longest matching prefix string.
Test the URI against regular expressions.
Stop processing when the first matching regular expression is found and use the corresponding location.
If no regular expression matches, use the location corresponding to the stored prefix string.
A typical use case for the = modifier is requests for / (forward slash). If requests for / are frequent, specifying = / as the parameter to the location directive speeds up processing, because the search for matches stops after the first comparison.

A location context can contain directives that define how to resolve a request – either serve a static file or pass the request to a proxied server. In the following example, requests that match the first location context are served files from the /data directory and the requests that match the second are passed to the proxied server that hosts content for the www.example.com domain.

server {
    location /images/ {
        root /data;
    }

    location / {
        proxy_pass http://www.example.com;
    }
}

The root directive specifies the file system path in which to search for the static files to serve. The request URI associated with the location is appended to the path to obtain the full name of the static file to serve. In the example above, in response to a request for /images/example.png, NGINX Plus delivers the file /data/images/example.png.

The proxy_pass directive passes the request to the proxied server accessed with the configured URL. The response from the proxied server is then passed back to the client. In the example above, all requests with URIs that do not start with /images/ are be passed to the proxied server.

Root Directory and Index Files

The root directive specifies the root directory that will be used to search for a file. To obtain the path of a requested file, NGINX appends the request URI to the path specified by the root directive. The directive can be placed on any level within the http {}, server {}, or location {} contexts. In the example below, the root directive is defined for a virtual server. It applies to all location {} blocks where the root directive is not included to explicitly redefine the root:

server {
    root /www/data;

    location / {
    }

    location /images/ {
    }

    location ~ .(mp3|mp4) {
        root /www/media;
    }
}

Here, NGINX searches for a URI that starts with /images/ in the /www/data/images/ directory in the file system. But if the URI ends with the .mp3 or .mp4 extension, NGINX instead searches for the file in the /www/media/ directory because it is defined in the matching location block.

If a request ends with a slash, NGINX treats it as a request for a directory and tries to find an index file in the directory. The index directive defines the index file’s name (the default value is index.html). To continue with the example, if the request URI is /images/some/path/, NGINX delivers the file /www/data/images/some/path/index.html if it exists. If it does not, NGINX returns HTTP code 404 (Not Found) by default. To configure NGINX to return an automatically generated directory listing instead, include the on parameter to the autoindex directive:

location /images/ {
    autoindex on;
}

You can list more than one filename in the index directive. NGINX searches for files in the specified order and returns the first one it finds.

location / {
    index index.$geo.html index.htm index.html;
}

The $geo variable used here here is a custom variable set through the geo directive. The value of the variable depends on the client’s IP address.

To return the index file, NGINX checks for its existence and then makes an internal redirect to the URI obtained by appending the name of the index file to the base URI. The internal redirect results in a new search of a location and can end up in another location as in the following example:

location / {
    root /data;
    index index.html index.php;
}

location ~ .php {
    fastcgi_pass localhost:8000;
    #...
}

Here, if the URI in a request is /path/, and /data/path/index.html does not exist but /data/path/index.php does, the internal redirect to /path/index.php is mapped to the second location. As a result, the request is proxied.

So there is no precedence given to nested regex locations at all? What value does nesting provide then?

Nesting is to do thins like this:

location / {
# something generic stuff here

   location ~ .jpg$ {
       expires 1w;
   }
}

location /app1/ {
  # something special for app1 here, e.g.
  # access control / auth_basic … /access …

   location = /app1/login {
       # something special for /app1/login,
       # eveything from /app1/ is inherited

       proxy_pass ...
   }

   location ~ .jpg$ {
       expires 1m;
   }
}

location /app2/ {
# separate configuration for app2 here,
# changes in /app1/ doesn’t affect it
# ...

   location ~ .jpg$ {
       expires 1y;
   }
}

That is, it allows to write scalable configurations using prefix locations.
With such approach, you can edit anything under /app1/ without being concerned how it will affect things for /app2/.

It also allows to use inheritance to write shorter configurations, and allows to isolate regexp locations within prefix ones.

This seems like it should be a fairly simple thing to do.
Image/CSS requests to some folders get handled one way, and image/CSS requests to all other folders get handled another way.

See above for an example.

(I personally recommend using separate folder for images/css to be able to use prefix locations instead of regexp ones. But it should be relatively safe this way as well — as long as they are isolated in other locations. One of the big problems with regexp locations is that often they are matched when people don’t expect them to be matched, and isolating regexp locations within prefix ones minimizes this negative impact.)

This is an experimental pilot project for a datacenter conversion, and the use of regex to specify both the file types and folder names is mandatory. The project this pilot is for will eventually require more than 50 server blocks with hundreds of locations in each block if regex cannot be used. It would be an unmaintainable mess without regex.

Your problem is that you are trying to mix regex locations and prefix locations without understanding how they work, and to make things even harder you add nested locations to the mix.

Instead, just stop doing things harder. Simplify things.

Most recommended simplification is to avoid regexp location. Note that many location blocks isn’t necessary bad thing. Sometimes it’s much easier to handle hundreds of prefix location blocks than dozens of regexp locations. Configuration with prefix locations are much easier to maintain.

If you can’t avoid regexp locations for some external reason, it would be trivial to write a configuration which does what you want with regexp locations as well:

location / {
    ...
}

location ~ ^/app1/ {
    ...
    location ~ .jpg$ {
        expires 1m;
    }
}

location ~ ^/app2/ {
    ...
    location ~ .jpg$ {
        expires 1y;
    }
}

location ~ .jpg$ {
    expires 1w;
}

Though such configurations are usually much harder to maintain in contrast to ones based on prefix locations.

nginx stores static prefix locations in some kind of binary tree. This means that lookup is fast enough AND the order of the locations does not matter at all.
The latter allows to create a lot of easy maintainable locations.

Regex locations are processed in the order of appearance. This is slow and will become maintenance nightmare when configuration would eventually grow.

If configuration has to have regex locations it is better to isolate them inside static prefix locations.

try_files

Syntax: try_files file … uri;
try_files file … =code;
Default: —
Context: server, location

Checks the existence of files in the specified order and uses the first found file for request processing; the processing is performed in the current context. The path to a file is constructed from the file parameter according to the root and alias directives. It is possible to check directory’s existence by specifying a slash at the end of a name, e.g. “$uri/”. If none of the files were found, an internal redirect to the uri specified in the last parameter is made. For example:

location /images/ {
    try_files $uri /images/default.gif;
}

location = /images/default.gif {
    expires 30s;
}

The last parameter can also point to a named location, as shown in examples below. Starting from version 0.7.51, the last parameter can also be a code:

location / {
    try_files $uri $uri/index.html $uri.html =404;
}

Example in proxying Mongrel:

location / {
    try_files /system/maintenance.html
              $uri $uri/index.html $uri.html
              @mongrel;
}

location @mongrel {
    proxy_pass http://mongrel;
}

Example for Drupal/FastCGI:

location / {
    try_files $uri $uri/ @drupal;
}

location ~ .php$ {
    try_files $uri @drupal;

    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;
    fastcgi_param SCRIPT_NAME     $fastcgi_script_name;
    fastcgi_param QUERY_STRING    $args;

    ... other fastcgi_param's
}

location @drupal {
    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to/index.php;
    fastcgi_param SCRIPT_NAME     /index.php;
    fastcgi_param QUERY_STRING    q=$uri&$args;

    ... other fastcgi_param's
}

In the following example,

location / {
    try_files $uri $uri/ @drupal;
}

the try_files directive is equivalent to

location / {
    error_page 404 = @drupal;
    log_not_found off;
}

And here,

location ~ .php$ {
    try_files $uri @drupal;

    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;

    ...
}

try_files checks the existence of the PHP file before passing the request to the FastCGI server.

Example for WordPress and Joomla:

location / {
    try_files $uri $uri/ @wordpress;
}

location ~ .php$ {
    try_files $uri @wordpress;

    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;
    ... other fastcgi_param's
}

location @wordpress {
    fastcgi_pass ...;

    fastcgi_param SCRIPT_FILENAME /path/to/index.php;
    ... other fastcgi_param's
}

try_files

tries the literal path you specify in relation to the defined root directive
and sets the internal file pointer.

If you use for instance

try_files /app/cache/ $uri @fallback;

with

index index.php index.html;

then it will test the paths in this order:

  • $document_root/app/cache/index.php
  • $document_root/app/cache/index.html
  • $document_root$uri

Trying Several Options

The try_files directive can be used to check whether the specified file or directory exists; NGINX makes an internal redirect if it does, or returns a specified status code if it doesn’t. For example, to check the existence of a file corresponding to the request URI, use the try_files directive and the $uri variable as follows:

server {
    root /www/data;

    location /images/ {
        try_files $uri /images/default.gif;
    }
}

The file is specified in the form of the URI, which is processed using the root or alias directives set in the context of the current location or virtual server. In this case, if the file corresponding to the original URI doesn’t exist, NGINX makes an internal redirect to the URI specified by the last parameter, returning /www/data/images/default.gif.

The last parameter can also be a status code (directly preceded by the equals sign) or the name of a location. In the following example, a 404 error is returned if none of the parameters to the try_files directive resolve to an existing file or directory.

location / {
    try_files $uri $uri/ $uri.html =404;
}

In the next example, if neither the original URI nor the URI with the appended trailing slash resolve into an existing file or directory, the request is redirected to the named location which passes it to a proxied server.

location / {
    try_files $uri $uri/ @backend;
}

location @backend {
    proxy_pass http://backend.example.com;
}

For more information, watch the Content Caching webinar on‑demand to learn how to dramatically improve the performance of a website, and get a deep‑dive into NGINX’s caching capabilities.

A very common try_files line which can be applied on your condition is

location / {
    try_files $uri $uri/ /test/index.html;
}

you probably understand the first part, location / matches all locations, unless it’s matched by a more specific location, like location /test for example,

The second part ( the try_files ) means when you receive a URI that’s matched by this block try $uri first, for example http://example.com/images/image.jpg nginx will try to check if there’s a file inside /images called image.jpg if found it will serve it first.

Second condition is $uri/ which means if you didn’t find the first condition $uri try the URI as a directory, for example http://example.com/images/, ngixn will first check if a file called images exists then it wont find it, then goes to second check $uri/ and see if there’s a directory called images exists then it will try serving it.

Side note: if you don’t have autoindex on you’ll probably get a 403 forbidden error, because directory listing is forbidden by default.

EDIT: I forgot to mention that if you have index defined, nginx will try to check if the index exists inside this folder before trying directory listing.

Third condition /test/index.html is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html inside the folder test and serve it if it exists.

If the third condition fails too, then nginx will serve the 404 error page.

Also there’s something called named locations, like this

You can call it with try_files like this

try_files $uri $uri/ @error;

TIP: If you only have 1 condition you want to serve, like for example inside folder images you only want to either serve the image or go to 404 error, you can write a line like this

location /images {
    try_files $uri =404;
}

which means either serve the file or serve a 404 error, you can’t use only $uri by it self without =404 because you need to have a fallback option.

You can also choose which ever error code you want, like for example:

location /images {
    try_files $uri =403;
}

This will show a forbidden error if the image doesn’t exist, or if you use 500 it will show server error, etc ..

  1. 21.11.2010, 18:33


    #1

    По умолчанию Последнее обновление и конфиг nginx (@fallback)

    После обновления, вылезла бяка с @fallback в конфиге nginx. Его вынесли в основную секцию server.

    Код:

            server {
                    listen ip:80;
                    server_name hostname.spb.ru www.hostname.spb.ru *.hostname.spb.ru;
                    rewrite ^(/manager/.*)$ https://$host$1 permanent;
                    error_page 404 = @fallback;
                    location / {
                            limit_req   zone=one  burst=6;
                            #access_log /var/log/nginx/hostname.spb.ru www.hostname.spb.ru *.hostname.spb.ru IP; # DDoS Protection
                            proxy_pass http://ip:8080;
                            proxy_redirect http://hostname.spb.ru:8080/ /;
                            proxy_set_header Host $host;
                            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                            proxy_set_header X-Real-IP $remote_addr;
                    }
                    location ~ /.ht {
                    }
                    location ~* ^/(webstat/|awstats|webmail/|myadmin/|manimg/) {
                            proxy_pass http://ip:8080;
                            proxy_redirect http://hostname.spb.ru:8080/ /;
                            proxy_set_header Host $host;
                            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                            proxy_set_header X-Real-IP $remote_addr;
                    }
                    location  ~* ^.+.(bmp|jpg|jpeg|pjpeg|gif|ico|cur|png|css|doc|txt|js|docx|rtf|ppt|pdf|svg|swf|3gp|dll|msi|cdr|cdd|cue|cdi|mkv|nrg|pdi|mds|mdf
                            root /var/www/hostname/data/www/hostname.spb.ru;
                            access_log /var/www/httpd-logs/hostname.spb.ru.access.log;
                    }
                    location @fallback {
                            proxy_pass http://ip:8080;
                            proxy_set_header Host $host;
                            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                            proxy_set_header X-Real-IP $remote_addr;
                    }
            }

    теперь на ВСЕ ошибки 404 реагирует nginx.
    Т.о.
    1) собственные страницы ошибок не работают (выставленные через ISPManager)
    2) клиентские RewriteRule тоже частично не фурычат (особенно на CMS DatalifeEngine)

    если вернуть как было:

    Код:

            server {
                    listen ip:80;
                    server_name hostname.spb.ru www.hostname.spb.ru *.hostname.spb.ru;
                    rewrite ^(/manager/.*)$ https://$host$1 permanent;
                    
                    location / {
                            limit_req   zone=one  burst=6;
                            #access_log /var/log/nginx/hostname.spb.ru www.hostname.spb.ru *.hostname.spb.ru IP; # DDoS Protection
                            proxy_pass http://ip:8080;
                            proxy_redirect http://hostname.spb.ru:8080/ /;
                            proxy_set_header Host $host;
                            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                            proxy_set_header X-Real-IP $remote_addr;
                    }
                    location ~ /.ht {
                    }
                    location ~* ^/(webstat/|awstats|webmail/|myadmin/|manimg/) {
                            proxy_pass http://ip:8080;
                            proxy_redirect http://hostname.spb.ru:8080/ /;
                            proxy_set_header Host $host;
                            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                            proxy_set_header X-Real-IP $remote_addr;
                    }
                    location  ~* ^.+.(bmp|jpg|jpeg|pjpeg|gif|ico|cur|png|css|doc|txt|js|docx|rtf|ppt|pdf|svg|swf|3gp|dll|msi|cdr|cdd|cue|cdi|mkv|nrg|pdi|mds|mdf
                            root /var/www/hostname/data/www/hostname.spb.ru;
                            access_log /var/www/httpd-logs/hostname.spb.ru.access.log;
                            error_page 404 = @fallback;
                    }
                    location @fallback {
                            proxy_pass http://ip:8080;
                            proxy_set_header Host $host;
                            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                            proxy_set_header X-Real-IP $remote_addr;
                    }
            }

    то всё работает прекрасно!!!!

    Как быть теперь в такой ситуации? Каждый раз при создании www домена лезть в конфиги nginx и всё править?
    Конфиг всех серверов в подписе.

    Хостинг ИНДАХОСТ
    BillManager Adv (beta) / ISPManager PRO (beta) / DNSManager (beta) / VDSManager (beta) / IPManager (beta)
    CentOS x86_64 / Apache mpm-itk + Nginx


  2. 21.11.2010, 21:07


    #2

    По умолчанию

    Что-то у вас не так срабатывает. У нас все прекрасно работает и с новым конфигом.

    Стоит один раз попробовать что бы влюбиться… в ISP.

    На все мои сообщения, действует конфигурация сервера: ISP Pro (всегда актуальная current версия), FreeBSD 8.0, php as fcgi, nginx+apache.

    Бесплатные плагины для ISPmanager.


  3. 22.11.2010, 04:23


    #3

    Alex Keda вне форума


    Senior Member

    Аватар для Alex Keda


    По умолчанию

    вы сами себе противоречите
    если на 404 стоит фаллбак — то на ошибки реагирует бакэнд, а не фронтэнд.

    поищщите — была такая же тема несколько недель назад.
    оказалось что там какая-то опция включена была в конфиге нгинкса

    Убей их всех! Бог потом рассортирует…


  4. 23.11.2010, 19:18


    #4

    По умолчанию

    Потеряшка нашлась. В конфиге NGINX был указан лишний параметр для proxy:

    proxy_intercept_errors on;

    В связи с этим, все ошибки выше 400 обрабатывал nginx.
    После того, как его закомментировал — всё нормально стало работать!!!! =)

    Всем спасибо, тему можно закрыть. =)

    Последний раз редактировалось netduke; 23.11.2010 в 19:29.

    Хостинг ИНДАХОСТ
    BillManager Adv (beta) / ISPManager PRO (beta) / DNSManager (beta) / VDSManager (beta) / IPManager (beta)
    CentOS x86_64 / Apache mpm-itk + Nginx


  5. 01.12.2010, 02:09


    #5

    evgen вне форума


    Junior Member


    Thumbs down

    Мне тоже вылезло это обновление боком.

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

    Код:

                   location @fallback {
                            proxy_pass http://123.123.123.123:8080;
                            proxy_set_header Host $host;
                            proxy_set_header X-Real-IP $remote_addr;
                            proxy_set_header X-Forwarded-For $http_x_forwarded_for;
                            proxy_pass_header Content-Type;
                            proxy_pass_header Content-Disposition;
                            proxy_pass_header Content-Length;
                    }
                    error_page 500 502 503 504      /50x.html;
                    error_page 404 = @fallback;
                    location = /50x.html {
                            root        /usr/share/nginx/html;
                    }
             }


  6. 01.12.2010, 16:22


    #6

    Alex Keda вне форума


    Senior Member

    Аватар для Alex Keda


    По умолчанию

    в последней бете — всё нормально
    альфы не юзаю, не знаю.

    Убей их всех! Бог потом рассортирует…


  7. 01.12.2010, 16:45


    #7

    inshu вне форума


    Developer team

    Аватар для inshu


    По умолчанию

    evgen, какая у вас версия?


  8. 02.12.2010, 11:29


    #8

    Lorelei вне форума


    Developer team


    По умолчанию

    Цитата Сообщение от evgen
    Посмотреть сообщение

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

    Конфиг выглядит правильно. Если у вас это влияет на работоспособность, то пишите о проблемах.


  9. 09.12.2010, 02:35


    #9

    WEB вне форума


    Junior Member


    Отправить сообщение для WEB с помощью ICQ

    По умолчанию

    Не стал создавать отдельную тему.
    Подскажите в чем может быть проблема.
    При установке nginx он не подхватывает существующие домены и создает почти пустой конфиг. Пробывал несколько раз устанавливать, включать/выключать.
    При установке в сервисах ispmanager гаснет лампочка apache2, хотя сайты грузятся. Система Debian 5.


  10. 09.12.2010, 09:05


    #10

    GakcaT вне форума


    Senior Member


    По умолчанию

    2 Web
    Покажите логи /usr/local/ispmgr/var/ispmgr.log и /usr/local/ispmgr/var/pkgctl.log, которые генерируются при выполнении данных действий. Тогда можно будет сказать что-то определенное.
    И было бы гораздо лучше, если бы Вы создали отдельную тему.

    Последний раз редактировалось GakcaT; 09.12.2010 в 09:08.


Как я вижу, тебя интересует настройка nginx, и в этой статье я постараюсь тебе помочь кое в чём разобраться. А именно — с nginx директивой location, её назначением и синтаксисом.

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

Итак, директива location служит для установки конфигурации в зависимости от URI-запроса.

Синтаксис location в общем виде следующий:

Syntax:   location [=|~|~*|^~] uri { ... }
          location @name { ... }
Context: server, location

Как видите, операторы соответствия расположены в квадратных скобках, что значит, что они опциональны, их может и не быть в некоторых расположениях.

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

Префикс «@» («собака») определяет именованные расположения. Такие location’ы не используются для обработки обычных запросов. Вместо этого они используются для перенаправления запросов (пример №6). Они не могут быть вложенными и содержать в себе вложенные.

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

Логика работы

Логика работы nginx при определением нужного расположения такова: сначала он ищет соответствия URI со строковыми location’ами. Если он нашёл подходящий строковый литерал с оператором соответствия «=», поиск завершается. Иначе, запомнив удовлетворяющий (если такой нашелся) максимальной длины, сравнивает с местоположениями, заданными через регулярные выражения в порядке их следования в конфигурационном файле. Если одно из регулярных выражений удовлетворило запрашиваемому ресурсу, поиск больше не продолжается. Если же ни одна регулярка не подошла, выбирается сохранённая на первом шаге строка максимальной длины.

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

"~" (тильда) - для регистрозависимого соотношения URI (case sensitive matching)
"~*" (тильда звёздочка) - для регистроНЕзависимого соотношения URI (case insensitive matching)

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

На заметку: Nginx умеет декодировать URI налету. Например, для URI «/my/nginx/%20%20%20/logo.png» для определения location можно использовать «/my/nginx/   /logo.png».

Nginx location со строковыми литералами

Префикс «=» предназначен для строгого соответствия между запрошенным URI и значением location. Если они полностью совпадают, поиск сразу же прекращается.

На заметку: Если в проекте выяснилось, что на адрес «/» переходят очень часто, то для увеличения производительности будет лучше сделать строковый литерал. Например, вместо расположения location / для URI «/» использовать location = /. Это ускорит обработку, т.к. nginx на строгом совпадении с «/» завершит поиск и не будет пытаться вести поиск в других location’ах.

Выделение переменной

При соотношении URI с расположением через регулярные выражения можно выделять некоторые фрагменты строки в переменную. Как это сделать можно посмотреть в примере №7).

Примеры использования location

# Пример конфигурации №1. Для корневого URI «/»

location = / {
    # Расположение только для URI /
    # При совпадении дальнейший поиск не осуществляется
}

# Пример конфигурации №2. Базовый location

location / {
    # Совпадает с URI всех запросов, т.к. они все начинаются с "/"
    # Но! Если будут найдены соответствия в расположениях
    # с регулярными выражениями или с другим более длинным
    # строковым литералом (например, "/data/"), 
    # то конфигурация для "/" не будет применена.
}

# Пример конфигурации №3. Для URI вида «/data/.*»

location /data/ {
    # Это расположение соответствует всем URI, начинающихся с "/data/"
    # и продолжает поиск по оставшимся location'ам.
    # В этом примере регулярные выражения и другие строковые литералы
    # также будут проверены, и "location /data/" будет использован,
    # если более конкретизирующие расположения не удовлетворят искомому ресурсу.
}

# Пример конфигурации №4. Для URI вида «/img/.*»

location ^~ /img/ {
    # Соответствует любому URI, начинающемуся с "/img/".
    # Если соответствие установлено - останавливает дальнейший поиск,
    # не проверяя регулярные выражения, т.к. используется
    # префикс ^~ "крышечка/циркумфлекс тильда".
}

# Пример конфигурации №5. Для графических форматов

location ~* .(png|ico|gif|jpg|jpeg)$ {
    # Данное расположение соответствует всем запрашиваемым URI,
    # оканчивающихся ".png", ".ico", ".gif", ".jpg" или ".jpeg".
    # При этом надо заметить, что запросы внутри расположения "/img/"
    # будут обработаны в location из примера №4
    # Т.е., если расположения из примеров №4 и №5 разместить в таком же
    # порядке в реальном конфиге, то до этого расположения ресурсов 
    # дойдут только те картинки, которые лежат вне расположения "/img/"
}

# Пример конфигурации №6. Именованный location

location / {
    error_page 404 = @fallback;
}

location @fallback {
    # Если при внутреннем перенаправлении не нужно менять URI,
    # то можно передать обработку ошибки в именованный location
}

# Пример конфигурации №7. Выделение переменной

location ~ ^/a/(?<myvar>[a-zA-Z]+) {
   # Тут можно использовать переменную $myvar,
   # которая представляет из себя строку из латиницы
   if ($myvar = "sth") { ... }
}

Примеры реальных nginx location’ов

Anti-hotlinking

Директива location для Anti-hotlinking (борьбы с использованием ресурсов с вашего сервера на сторонних ресурсах. Такой способ использования ваших сетевых ресурсов называется hotlinking). Такое поведение хитрых разработчиков может заметно увеличить нагрузку на ваш сервер. Конфигурация:

location ~ .(gif|png|jpe?g)$ {
    valid_referers none blocked mywebsite.com *.mywebsite.com;
    if ($invalid_referer) {
       return 403;
    }
}

Запрет на скрипты внутри директорий

Следующий пример — запрет на скрипты в разрешённых для записи директориях:

location ~* /(images|cache|media|logs|tmp)/.*.(php|pl|py|jsp|asp|sh|cgi)$ {
    error_page 403 /403.htm;
    return 403;
}

Включение autoindex

В следующем примере location используется для включения autoindex в nginx (Разрешение на вывод листинга каталога):

location /list_dir {
    autoindex on;
    autoindex_exact_size off;
    autoindex_localtime on;
}

Заключение

Как видишь, при помощи location в nginx можно очень точечно или наоборот фрагментированно настраивать ресурс.

Если эта статья тебя так увлекла, что захотелось изучить эту тему более детально, обратись к официальной документации по location в nginx. Также можешь почитать инструкцию по созданию виртуальных хостов в nginx.

Спасибо, что дочитал статью до конца! Надеюсь, что она тебе понравилась! Не забудь задать вопросы в комментариях и поделиться ссылкой с друзьями! :)

Понравилась статья? Поделить с друзьями:
  • Error package javax xml bind annotation does not exist
  • Error package javax mail does not exist
  • Error package android support annotation does not exist
  • Error p13 apc
  • Error p audio capture client fl studio