Ошибка 504 nginx

Код ошибки в формате 5хх говорит о том, что на стороне сервера есть проблема: сервер не может обработать запрос от клиента. Клиентом в данном случае выступает браузер.Ошибка 504 Gateway Time Out возникает, когда в заданный промежуток времени сервер не получает ответ от другого сервера,…

Код ошибки в формате 5хх говорит о том, что на стороне сервера есть проблема: сервер не может обработать запрос от клиента. Клиентом в данном случае выступает браузер.

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




Ошибка 504 что значит

Какие ещё бывают варианты отображения ошибки:

  • HTTP Error 504,
  • Gateway Timeout Error,
  • HTTP Error 504 – Gateway Timeout,
  • 504 Gateway Timeout nginx,
  • 504 Gateway Time-out – The server didn’t respond in time,
  • Ошибка 504 Время ответа сервера истекло,
  • Время ожидания шлюза (504),
  • Ошибка тайм-аута шлюза,
  • HTTP 504,
  • 504 Ошибка.

В этой статье мы расскажем, как устранить код ошибки 504.

Как исправить ошибку 504 посетителю сайта

Итак, вы перешли на сайт, но вместо веб-страницы видите сообщение с кодом 504.




Что такое тайм аут шлюза

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

1) Обновите страницу. Но обновите не клавишей F5, а выделите содержимое адресной строки и нажмите Enter. Если после этих действий ошибка 504 не возникает ни на текущем, ни на любом другом сайте – её можно проигнорировать.

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

3) Очистите кэш браузера и удалите файлы cookie. После этого браузер будет работать быстрее.
Воспользуйтесь инструкцией Как очистить кэш браузера.

4) Перезагрузите роутер или модем. Отключите устройство от сети примерно на 10 минут.

5) Очистите кэш DNS. Для этого воспользуйтесь инструкцией ниже.


Как очистить кэш DNS

В зависимости от вашей операционной системы очистите кэш по одной из инструкций.

1) Откройте командную строку. Для этого введите в поисковую строку «Командная строка» и выберите появившееся приложение:




2) Введите команду:

3) Дождитесь сообщения об очистке кэша:




1) Откройте терминал клавишами Ctrl+Alt+T.

2) Введите команду:

Для Ubuntu:

sudo service network-manager restart

Для других дистрибутивов:

sudo /etc/init.d/nscd restart

1) Войдите в терминал. Для этого нажмите клавиши Command + Space. Введите Терминал и нажмите на найденное приложение.

2) Введите команду:

sudo killall -HUP mDNSResponder

Готово, вы очистили кэш DNS.

6) Обратитесь в техподдержку вашего интернет-провайдера. Возможно, это проблема сети, за которую отвечает провайдер.

Если эти действия не принесли результата – обратитесь в техническую поддержку сайта.

Если вы владелец сайта

Как исправить ошибку 504 на виртуальном хостинге

1 способ

Эта ошибка может возникнуть в случае, если для Nginx был превышен лимит на время ответа сайта. По умолчанию это 30 секунд, при этом среднее время загрузки сайта не должно превышать 1-3 секунды.
Если скрипты вашего сайта должны исполняться дольше 30 секунд, вы можете миновать Nginx и обратиться к сайту по другим портам. Если ваша панель управления хостингом:

  • ISPManager – используйте порт 8081
  • cPanel или Plesk – используйте порт 8080.

2 способ

Если этот вариант вам не подходит, рекомендуем перенести ваш сайт на Облачный сервер, на котором доступна гибкая настройка сервера, в том числе и лимитов. Для этого закажите услугу «Облачные серверы» и перенесите сайт по инструкции Как перенести сайты между услугами REG.RU.

3 способ

Также вы можете изменить директиву max_execution_time в файле php.ini. Она указывает на время, за которое должен отрабатываться скрипт. Для этого:

  1. 1.

  2. 2.

    Укажите нужное значение в строке:

    Где 30 – время выполнения скрипта в секундах.

4 способ

Если вы используете CDN, проблема может быть связана с ней.


Что такое CDN

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

  • Если в кэше PoP есть данные об этом запросе, он отвечает браузеру, а тот отображает контент.
  • Если в кэше этого сервера нет данных, запрос переадресовывается к ориджину – центральному серверу, на котором хранятся все данные. Когда ориджин отвечает на запрос, PoP кэширует его и передаёт ответ браузеру. После этого контент отображается в браузере.

Ошибку 504 может вернуть кэширующий сервер, если превышено время ожидания от центрального сервера.

Если ошибку исправить не удалось, обратитесь в техническую поддержку.

Как исправить ошибку 504 на VPS

1 способ

Эта ошибка может возникнуть в случае, если для Nginx был превышен лимит на время ответа сайта. По умолчанию это 30 секунд, при этом среднее время загрузки сайта не должно превышать 1-3 секунды.
Чтобы избавиться от этой ошибки, попробуйте повысить время ожидания веб-сервера Nginx.

2 способ

Также ошибка 504 может возникать, когда Nginx используется как прокси-сервер для Apache. В этом случае нужно настроить параметры времени ожидания при проксировании. Максимальное время исполнения скрипта в настройках веб-сервера — 300 секунд.
Изменить параметры ожидания можно в конфигурационном файле nginx.conf. Для этого:

  1. 1.

    Подключитесь к серверу по SSH.

  2. 2.

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

    sudo nano /etc/nginx/nginx.conf
  3. 3.

    Добавьте строки в блоке server:

    #server {
    
    #...
    
    proxy_connect_timeout 600;
    proxy_send_timeout 600;
    proxy_read_timeout 600;
    send_timeout 600;
    
    #...
    #}

    Где 600 — время в секундах.

  4. 4.

    Перезапустите Nginx с помощью команды:

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

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

Именно в таком режиме может наблюдаться ошибка 504 gateway time out Nginx. В нашей сегодняшней статье мы попытаемся разобраться почему она возникает и как с ней бороться. Разберем несколько способов решения и причин.

Как я уже сказал, такая ошибка возникает, когда сервер Nginx работает в режиме прокси. Например, при использовании php-fpm или Apache. Дословно, она означает, что превышено время ожидания ответа от сервера. В нашем случае, превышено время ожидания ответа от php-fpm. Рассмотрим несколько причин такого поведения:

  • Скрипт PHP или на другом языке полностью завис и уже не вернет никакого ответа;
  • Скрипт работает очень долго, но в Nginx настроен интервал на сброс соединения если целевой сервер не ответил на запрос за отведенный строк;
  • Сервер перегружен и не успевает обслужить всех клиентов, вернуть ответы на все запросы Nginx;

Дальше рассмотрим что можно сделать если вы встретились с ошибкой 504 gateway time out Nginx.

Как исправить 504 gateway time out Nginx?

Самый первый вариант — это если вашему серверу, php-fpm или apache не хватает ресурсов системы, например, памяти или процессора. Вы можете посмотреть свободную память с помощью команды free:

free -h

Нагрузку на процессор можно узнать командой htop:

htop

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

Второй вариант — это если так и было запланировано, чтобы скрипт работал долго. В таком случае нужно настроить Nginx, чтобы он дождался ответа от Apache или php-fpm. Для решения проблемы в случае с php-fpm нужно только добавить две строчки в блок настройки fastgci:

fastcgi_send_timeout 300;
fastcgi_read_timeout 300;

Здесь 300 означает 300 секунд, для большинства скриптов, этого будет вполне достаточно, но вы можете еще больше увеличить значение если это нужно. Также ошибка 504 может возникать, когда Nginx используется в качестве прокси для Apache или любого другого веб-сервера, тогда нужно еще настроить время ожидания для прокси. Добавьте эти строки в секцию server:

proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;

Тут уже мы задаем таймаут 600 секунд для различных видов действий — подключения, отправки данных, чтения данных и так далее. После завершения настройки Nginx стоит перезапустить:

sudo systemctl restart nginx

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

fgrep -i " 504 " /var/log/nginx/access.log

Более подробную информацию иногда можно увидеть в error.log:

fgrep -i " 504 " /var/log/nginx/error.log

Дальше, если проблема именно в php-fpm, вы можете отследить какие скрипты выполняются медленно с помощью встроенной функции slow-log. Для ее активации добавьте следующие строки в конфигурацию вашего пула:

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

slowlog = /var/log/php-fpm/www-slow.log
request_slowlog_timeout = 5s

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

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

Выводы

В этой статье мы рассмотрели как исправить 504 gateway time out Nginx 1.2 7, а также почему может возникнуть эта ошибка. Надеюсь, эта информация была полезной для вас.

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

Website errors are always a mess for users.

Sometimes the errors are completely clueless and users may not know how to fix it.

A typical example of such an error is “504 timeout error,” in Nginx, a tricky error to resolve.

That’s why, we often get requests from our customers to fix “504 timeout Nginx ” error as part of our Technical Support Services.

Today, let’s understand what is 504 timeout error in Nginx and reasons on why this error occurs, also the way Bobcares’ Engineers fix it.

What is 504 timeout Nginx error?

Nginx is an open-source, high-performance HTTP web server. Now, it is used for serving web pages, as reverse proxy, caching, load balancing, media streaming, and more.

Furthermore, a 504 Nginx timeout error is one of the HTTP status code. Usually, the server sends back a 504 HTTP code when the request is not completed.

In addition, this is a common error, most likely due to process exceeding the PHP execution time limit or the read timeout settings of FastCGI.

Top reasons for the “504 timeout error,” and quick fix for it in Nginx

From our experience in managing server, our Support Engineers often deal with this error and fixe it for our customers.

Now, let’s see how our Technical Team exactly fixed “504 timeout Nginx” error with different methods.

1. Adjustment in timeout settings

Usually, adjusting the timeout settings is one of the methods to fix 504 error.

Recently, in one of the customer’s server, Nginx was set up as a proxy server with PHP-FPM disabled. To fix the 504 error, we increased the timeout values in the file “timeout.conf”.

1.  We edited the file /etc/nginx/conf.d/timeout.conf and added the following parameters to file “timeout.conf”.

proxy_connect_timeout       600;
proxy_send_timeout          600;
proxy_read_timeout          600;
send_timeout                600;

2. Finally, we restarted the service.

service nginx restart

2. Modifying Other Nginx settings

Sometimes, increasing values in “timeout.conf” doesn’t resolve this issue. Then, our Support Engineers add codes in “nginx.conf”. In addition, if the values are already preset in “nginx.conf”, we will increase the value.

1. We open the file /etc/nginx.

2. Then, we add the following snippet to “timeout.conf”.

client_header_timeout 3000;
client_body_timeout 3000;
fastcgi_read_timeout 3000;
client_max_body_size 32m;
fastcgi_buffers 8 128k;
fastcgi_buffer_size 128k;

3. Finally, we restart the service.

service php-fpm restart
service nginx restart

3. Modification in PHP settings

At times, to fix  504 Nginx timeout error, we may need to modify the php settings in php.ini file.

Recently, our Support Engineers had to raise the value of max_execution_time  in php.ini file.

In CentOS, we located “/etc/php.ini” and  increased the value “max_execution_time” by adding the following entry.

max_execution_time = 150

Additionally, we raised the value of request_terminate_timeout setting in php.ini file too.

request_terminate_timeout = 150

4. Nginx virtual host configuration settings

Similarly, fix may involve modifying Nginx virtual host configuration too. Here, to fix the php file access, in Nginx virtual host configuration, our Support Engineers add FastCGI read timeout variable.

location ~* .php${
include fastcgi_params;
fastcgi_index index.php;
fastcgi_read_timeout 150;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

Then, we restart PHP-FPM and Nginx.

service php-fpm restart
service nginx restart

This removes the 504 error from the website and it starts working correctly.

[Getting 504 timeout error in Nginx? We are here to fix it.]

Conclusion

In short, a “504 timeout Nginx” error is one of the HTTP status code that a server sends back if the underlying request is not completed. Today, we saw how our Support Engineers fixed “504 timeout error” in Nginx.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

I use NGINX a lot. I recently deployed a Node.js web application with NGINX as a reverse proxy server for it. One of the key features of the application is support for data imports using excel templates. However, it didn’t take long before users uploading bulky files started getting a 504 Gateway Timeout error from NGINX.

[ You might also like: Fix Nginx Error: 413 Request Entity Too Large ]

Are you getting the same error? Don’t worry, I have got you covered. In this article, I will show how to fix the 504 Gateway Timeout error by increasing the request timeout in the NGINX web server.

Increase Request Timeout in NGINX for a Proxied Server

If you are using NGINX as a reverse proxy for an application server such as Node.js or a web server such as Apache or Gunicorn, then you can increase request timeout by setting the following parameters either in the http, or server, or location directive.

The timeout is in seconds and makes sure that you have to set timeout values that will work effectively and efficiently for your environment.

proxy_connect_timeout 75;
proxy_send_timeout 600;
proxy_read_timeout 600;

From the names of the directives, it is easy to tell what timeout they define. The proxy_connect_timeout directive states a timeout for creating a connection with a proxied server. According to the official NGINX documentation, the value should not exceed 75 seconds.

The next directive proxy_send_timeout defines a timeout for transmitting a request to the proxied server. The last directive proxy_read_timeout sets a timeout for reading a response from the proxied server.

Now that you have a slight understanding of the above directives, you can configure that as shown. In the http context, you can set them in NGINX’s main configuration file located at /etc/nginx/nginx.conf.

http{
....
	proxy_read_timeout 600;
	proxy_connect_timeout 600;
	proxy_send_timeout 600;
....
In the server context, you can define them in a server block file for your application for example /etc/nginx/conf.d/example.com.conf:
server{
....
             proxy_read_timeout 600;
	 proxy_connect_timeout 600;
	 proxy_send_timeout 600;

             location  /  {
                try_files $uri $uri/ /index.html =404 =403 =500;
          }
          location  /api  {
                proxy_pass http://127.0.0.1:5000;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header Host $host;
               proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                
       }
}

In a location block, they would look like this:

server{
....
             location  /  {
                try_files $uri $uri/ /index.html =404 =403 =500;
          }
          location  /api  {
                proxy_pass http://127.0.0.1:5000;
                proxy_read_timeout 600;
	        proxy_connect_timeout 600;
	        proxy_send_timeout 600;

               proxy_set_header X-Real-IP $remote_addr;
               proxy_set_header Host $host;
               proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       }
}

Save the file and close it.

To apply the recent changes, you need to restart the NGINX service.

$ sudo systemctl restart nginx
OR
# systemctl restart nginx

Increase Request Timeout in NGINX for FastCGI

For a FastCGI server such as PHP-FPM, you can use the following directive either in the http, or server, or location:

fastcgi_connect_timeout 75;
fastcgi_send_timeout 600;
fastcgi_read_timeout 600;

In a location block for processing PHP files, you can define them as shown:

location ~ .php$ {
	fastcgi_pass unix:/run/lib/php7.4-fpm.sock;
	fastcgi_index index.php;
	fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
	include fastcgi_params;
	fastcgi_connect_timeout 75;
            fastcgi_send_timeout 600;
            fastcgi_read_timeout 600;
}

Do not forget to restart the NGINX service after making changes:

$ sudo systemctl restart nginx
OR
# systemctl restart nginx

Note: You might also have to make some configuration changes in the php.ini and PHP-FPM pool configuration files especially to the max_execution_time and request_terminate_timeout directives respectively.

That’s it! In this article, we looked at how to increase request timeout in NGINX to solve the 504 Gateway timeout error. For more information, read the NGINX documentation. For any comments, reach us via the feedback form below.

  • Ошибка 504 ― что значит
  • Как устранить код ошибки 504 Gateway Time Out владельцу сайта
  • Долго обрабатывается скрипт
  • Проблемы с CDN
  • Выросла нагрузка на один из серверов
  • Проблемы с сайтами на WordPress
  • Что может сделать пользователь

Любой код ошибки, который начинается на цифру 5, говорит о том, что проблема возникла на стороне сервера. В этой статье мы рассмотрим ошибку 504 Gateway Time Out: откуда она появляется и как её исправить.

Ошибка 504 ― что значит

Ошибка 504 Gateway Time Out говорит о том, что в обработке запроса участвовало несколько серверов. Для выполнения запроса один из серверов должен был получить ответ от другого, но не получил его в течение максимально допустимого времени ожидания.

Также вы можете встретить другие варианты отображения ошибки:

  • HTTP Error 504,
  • Gateway Timeout Error,
  • HTTP Error 504 – Gateway Timeout,
  • 504 Gateway Timeout nginx,
  • Ошибка 504 Время ответа сервера истекло,
  • Время ожидания шлюза (504),
  • Ошибка тайм-аута шлюза.

Что такое тайм-аут шлюза

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

Как устранить код ошибки 504 Gateway Time Out владельцу сайта

Самые частые причины этой ошибки:

  • слишком долго выполняется скрипт,
  • CDN не может связаться с основным сервером,
  • неожиданно выросла нагрузка на один из серверов.

Все эти причины может устранить только владелец сайта. 

Долго обрабатывается скрипт

Конечно, лучше всего облегчить тяжёлый скрипт. Так он не будет нагружать сервер и вызывать ошибку. Однако не всегда есть возможность заменить его. В таком случае можно увеличить время ожидания сервера, чтобы весь скрипт успевал обрабатываться. По умолчанию максимальное время выполнения скрипта ― 30 секунд. Увеличить это время можно через PHP, настройки Nginx и Apache. 

PHP

Изменить время обработки запроса можно в директиве max_execution_time в файле php.ini. Чтобы изменить это время:

  1. Откройте файл php.ini.
  2. Добавьте строку:
max_execution_time = 60

Где 60 – время выполнения запроса  в секундах.

Nginx

Если вы используете Nginx, настройки времени обработки скрипта делаются в файле nginx.conf.

      1. Перейдите в файл nginx.conf. Для этого введите команду:

sudo nano /etc/nginx/nginx.conf

      2. Введите строки:

proxy_connect_timeout 600; 
proxy_send_timeout 600; 
proxy_read_timeout 600; 
send_timeout 600;

Где 600 – время выполнения скрипта в секундах.

      3. Перезапустите Nginx с помощью команды:

service nginx reload

Обратите внимание! Если вы меняете время обработки запроса в Nginx, рекомендуем увеличить и max_execution_time в php.ini. В параметрах укажите то же количество секунд, что и указали в nginx.conf.

Apache

Если вы используете Apache, увеличить время обработки запроса можно в файле httpd.conf. Для этого:

      1. Перейдите в файл httpd.conf.
      2. Введите: 

# Timeout: The number of seconds before receives and sends time out.
Timeout 600

Где 600 – время выполнения скрипта в секундах.

      3. Сохраните изменения и перезапустите Apache. 

Проблемы с CDN

CDN ― это множество связанных серверов, которые ускоряют передачу данных (фото, видео, скриптов) пользователю. CDN-серверы размещают как можно ближе к аудитории.

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

Если вы пользуетесь CDN и на вашем сайте 504-я ошибка, попробуйте отключиться от системы. Если сайт заработал, нужно обращаться в техническую поддержку сервиса, чтобы предупредить их о проблеме.

Также вместе с CDN часто используют прокси-сервер Cloudflare или Sucuri. Ошибка может появиться из-за них. Для её решения нужно обратиться в техподдержку сервиса.

Выросла нагрузка на один из серверов

Причин, почему возросла нагрузка на сервер, может быть три: 

  1. Повысился спрос на ваш товар. Это позитивная причина. Возможно, скоро праздники и все закупаются подарками, а ваш продукт пользуется спросом. Также посетителей может привлечь рекламная кампания. Для решения такой проблемы достаточно приобрести тариф хостинга или VPS с большей мощностью. Тогда сервер сможет принять большой поток клиентов.
  2. На вас была сделана DDoS-атака. Ваши недоброжелатели могут искусственно создать большой поток посетителей и вывести сайт из строя. На хостинге и VPS от 2DOMAINS есть встроенная защита от DDoS-атак.
  3. На сервере появился вирус. Вирусы могут нарушать работу сервера, перегружая его. Проверьте ваш сайт на вирусы. Если найдёте, удалите их и проверьте работоспособность сайта. 

Проблемы с сайтами на WordPress

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

Что может сделать пользователь

  1. Перезагрузите страницу. Если ошибка появилась из-за перегрузки сервера, вы можете подождать и зайти на сайт, когда наплыв посетителей закончится. Если ошибка связана с настройкой сервера, подождите, пока владелец не починит сайт.
  2. Откройте сайт на другом браузере. Неисправные или старые версии браузеров могут показывать разные ошибки, в том числе и 504-ю. Попробуйте открыть веб-ресурс на любом другом браузере. Если сайт заработает, проверьте обновление основного браузера или переустановите его.
  3. Откройте сайт на другом устройстве. Если проблема в самом устройстве, можно попробовать открыть сайт на смартфоне или другом ПК. Если сайт работает, проверьте корректность работы устройства и драйверов.
  4. Перезагрузите сетевые устройства. Временные проблемы с вашим модемом, маршрутизатором или другим сетевым оборудованием могут вызвать проблему 504 Gateway Timeout. Перезагрузка этих устройств может помочь.
  5. Очистите кэш браузера. Если вы часто встречаете разного рода ошибки на сайтах, возможно, проблема в переполненном кэше браузера. Со временем в любом браузере накапливается много «мусора», который нужно удалять. Очистить кеш вам помогут инструкции:
  • Как очистить кэш браузера,
  • Как очистить кэш браузера Safari.

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

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

Ошибка 504 Gateway Timeout (от англ. «тайм-аут шлюза») — это код состояния HTTP, который указывает на то, что веб-сервер не получил своевременного ответа от вышестоящего сервера при попытке загрузить страницу. Простыми словами, ошибка 504 Gateway Timeout — это свидетельство о сбое на сервере, когда он выступает шлюзом или в качестве прокси.

В нашей статье клиент — браузер, а сервер — специализированная или выделенная машина.

Как выглядит ошибка 504

В зависимости от конфигурации у ошибки 504 есть различные формы написания:

  • 504 Error.
  • «Время ответа сервера истекло».
  • HTTP Error 504.
  • «Ошибка таймаута шлюза».
  • Gateway timeout.
  • The server didn’t respond in time.

Точный текст ошибки зависит от того, какой именно сервер используется в качестве фронта и какой в качестве бэка. Самые частые сценарии — Nginx и Apache, соответственно.

Один из возможных вариантов ошибки

Один из возможных вариантов ошибки

Почему возникает ошибка 504

Самая популярная причина — перегрузка сервера. Давайте посмотрим, почему она происходит и какие источники встречаются наиболее часто.

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

Ошибки от плагинов

Многие веб-мастера устанавливают большое количество разнообразных плагинов для расширения функционала сайта. Например, для внедрения кеширования страниц или добавления на сайт CDN (сеть доставки контента). Подобные плагины могут загружать данные со сторонних источников — например, удаленных серверов. Если на таком сервере возникает сбой, определенная страница или сайт целиком может начать отдавать 504-ю ошибку.

Ошибки от скриптов

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

Аномальное увеличение посещаемости

Если на сайте резко увеличивается трафик, сервер может работать медленнее. Чем больше трафика, тем больше запросов к серверу. Со временем количество неотвеченных запросов только увеличивается, в итоге взаимодействие с сервером прекращается и отправляется код состояния 504 Bad Gateway.

Небольшие скачки посещаемости не представляют угрозы для производительности сервера

Небольшие скачки посещаемости не представляют угрозы для производительности сервера

Израсходование лимитов тарифного плана хостинга

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

Пример лимитов по серверным ресурсам на начальном тарифе хостинга Beget

Пример лимитов по серверным ресурсам на начальном тарифе хостинга Beget

Загрузка на сайт файлов

Каждый раз, когда вы обращаетесь к сайту через административную панель, статическая нагрузка на сервер повышается. Например, вы загружаете видео или большое количество изображений либо импортируете длинный список товаров в интернет-магазин XML-файлом.

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

Хакерские атаки

504 ошибку могут вызывать различные атаки на сайт — например, распределенная атака типа «отказ в обслуживании». Чтобы диагностировать эту причину — обратитесь в поддержку хостинга. Если атака подтвердится — установите на сайт защитный экран, например Cloudflare.

Схема атаки типа denial-of-service

Схема атаки типа denial-of-service

Вредоносный код в файлах сайта

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

Браузер Google Chrome не позволит открыть сайт, если он заражен вирусом или содержит иное вредоносное ПО

Браузер Google Chrome не позволит открыть сайт, если он заражен вирусом или содержит иное вредоносное ПО

Ошибка в браузере

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

Как исправить ошибку 504 вебмастеру

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

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

  1. Во первых: нужно обратиться в саппорт используемого хостинга и уточнить, не превышены ли лимиты по использованию ресурсов серверного железа на вашем аккаунте. Если вы укладываетесь в ограничения выбранного тарифного плана, то нужно искать другой источник появления 504-й.
  2. Во вторых: вспомните, какие глобальные изменения вы делали на сайте в последнюю неделю или две. Возможно вы меняли тему (дизайн) сайта, глобальный вид URL или устанавливали какие-либо плагины.

Если вы вспомнили конкретное изменение, просто откатитесь к предыдущей версии: например, удалите плагин или верните старую тему сайта.

«У меня VPS с Nginx / Apache»

С такой конфигурацией сервера возникновение 504 ошибки встречается довольно часто. Чтобы устранить ее, найдите конфигурационный файл сервера, который называется httpd.conf. Находится он в дистрибутиве Apache, соответственно. Что нужно сделать:

  1. Устанавливаем значение тайм-аута на 700 секунд и сохраняем файл. Перезагружаем бэкенд (для этого используем команду service nginx reload) и проверяем, ушла ошибка или нет.
  2. Находим файл php.ini. Открываем его и изменяем значение максимального времени исполнения на 300 секунд. Опять перезагружаем backend (используем команду service nginx reload) и проверяем, ушла ошибка или нет.

Параметр для значения Timeout устанавливаем на 700 секунд, а max_execution_time изменяем на 300 секунд

Параметр для значения Timeout устанавливаем на 700 секунд, а max_execution_time изменяем на 300 секунд

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

Изменение портов в панели управления хостингом

Также попробуйте изменить порты для обращения к сайту. Так вы решите проблему в случаях, когда выполнение скрипта занимает продолжительное время (более 30 секунд). В разных панелях управления хостингом нужно устанавливать разные порты. Например в Plesk — это 8080, в ISPManager — 8081.

Примеры портов для Plesk

Примеры портов для Plesk

«У меня на сайте используются CDN: что делать»

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

Два типа дистрибуции контента сайта. CDN справа

Два типа дистрибуции контента сайта. CDN справа

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

Если изменить значение максимального времени исполнения в php.ini для вас затруднительно, вы можете просто перейти на облачный тариф хостинга. В облачной инфраструктуре доступно тонкое управление параметрами сервера, включая регулировку технических ограничений.

Пример конфигураций облачных серверов у Selectel

Пример конфигураций облачных серверов у Selectel

Включите журналирование ошибок

Этот способ поможет точно установить, в каком именно месте происходит ошибка, не позволяющая открыть страницу. В CMS журналирование может активироваться разными способами. Например, на WordPress необходимо открыть файл wpconfig.php и добавить в него три PHP-константы для установки отладки:

define( ‘wp_debug’, true );

define( ‘wp_debug_log’, true );

define( ‘wp_debug_display’, false );

Сохраняем wpconfig.php. Все, теперь логирование ошибок включено и вы сможете посмотреть источник ошибки в журнале.

«У меня веб-сервер nginx: что делать»

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

  • таймаута для отправки прокси;
  • тайм-аута для чтения прокси;
  • времени отправки тайм-аута.

Мы установили значение для каждого вышеописанного параметра на 750 секунд

Мы установили значение для каждого вышеописанного параметра на 750 секунд

Обычно конфигурационный файл тайм-аута находится в следующей директории:

Найдите конфигурационный файл Nginx по этому пути

Найдите конфигурационный файл Nginx по этому пути

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

Если вы используете VPS, необязательно вручную искать конфигурационный файл, чтобы изменить значение параметров. Просто откройте административную панель сервера, найдите настройки сервера и добавьте необходимые значения. Как правило, настройки php.ini и параметры httpd всегда разнесены по разным вкладкам. Справедливо это для ISPmanager, Ajenti, Vesta Control Panel и других популярных панелей управления сервером, например, CentOS Web Panel.

Неполадки сервера

Создайте тикет в саппорте хостинга и уточните, существуют ли на данный момент какие-либо неполадки с сервером. Это довольно редкий сценарий, но проверить его также необходимо, если ошибку не удалось устранить вообще никакими из вышеописанных способов.

Пример обращения в саппорт хостинга

Пример обращения в саппорт хостинга

Как исправить ошибку 504 пользователю

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

Очистка DNS

Очистите кэш DNS в используемой операционной системе:

  • На macOS необходимо открыть «Терминал» и указать команду sudo killall -HUP mDNSResponder.
  • На Windows нужно открыть командную строку и ввести команду: ipconfig /flushdns.

Очистка сопоставителя DNS в Windows 10

Очистка сопоставителя DNS в Windows 10

Другие способы

Если очистка DNS-кэша не помогла, попробуйте выполнить следующие действия

  1. Обновите страницу с очисткой ее кэша. Для этого используется сочетание горячих клавиш Control + F5. В редких случаях в кэше могут накапливаться ошибки, особенно если вы часто посещали сайт, на котором теперь возникает ошибка.
  2. Попробуйте открыть проблемную страницу с другого устройства. В редких случаях в системе могут накапливаться ошибки, которые препятствуют открытию всего сайта или конкретной страницы. Диагностировать эту причину и поможет смена устройства.
  3. Удалите временные файлы браузера, включая кэш-файлы и файлы-куки.

В Google Chrome удалить файлы cookie и другие данные сайта, можно в разделе Конфиденциальность и безопасность

В Google Chrome удалить файлы cookie и другие данные сайта, можно в разделе Конфиденциальность и безопасность

Заключение: профилактика появления Gateway timeout для вебмастера

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

  • Какие ресурсы серверного железа вы планируете использовать.
  • Что хотите настраивать.
  • Наличие каких технологий для вас является критически важным.

Так вы сможете выбрать максимально подходящий и быстрый сервер под свои задачи. Ну а 504 ошибка точно не будет появляться на сайте.

Содержание

  1. Как исправить 504 gateway time out Nginx
  2. Что значит 504 gateway time out Nginx?
  3. Как исправить 504 gateway time out Nginx?
  4. Выводы
  5. Module ngx_http_core_module
  6. Directives
  7. Embedded Variables

Как исправить 504 gateway time out Nginx

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

Именно в таком режиме может наблюдаться ошибка 504 gateway time out Nginx. В нашей сегодняшней статье мы попытаемся разобраться почему она возникает и как с ней бороться. Разберем несколько способов решения и причин.

Что значит 504 gateway time out Nginx?

Как я уже сказал, такая ошибка возникает, когда сервер Nginx работает в режиме прокси. Например, при использовании php-fpm или Apache. Дословно, она означает, что превышено время ожидания ответа от сервера. В нашем случае, превышено время ожидания ответа от php-fpm. Рассмотрим несколько причин такого поведения:

  • Скрипт PHP или на другом языке полностью завис и уже не вернет никакого ответа;
  • Скрипт работает очень долго, но в Nginx настроен интервал на сброс соединения если целевой сервер не ответил на запрос за отведенный строк;
  • Сервер перегружен и не успевает обслужить всех клиентов, вернуть ответы на все запросы Nginx;

Дальше рассмотрим что можно сделать если вы встретились с ошибкой 504 gateway time out Nginx.

Как исправить 504 gateway time out Nginx?

Самый первый вариант — это если вашему серверу, php-fpm или apache не хватает ресурсов системы, например, памяти или процессора. Вы можете посмотреть свободную память с помощью команды free:

Нагрузку на процессор можно узнать командой htop:

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

Второй вариант — это если так и было запланировано, чтобы скрипт работал долго. В таком случае нужно настроить Nginx, чтобы он дождался ответа от Apache или php-fpm. Для решения проблемы в случае с php-fpm нужно только добавить две строчки в блок настройки fastgci:

fastcgi_send_timeout 300;
fastcgi_read_timeout 300;

Здесь 300 означает 300 секунд, для большинства скриптов, этого будет вполне достаточно, но вы можете еще больше увеличить значение если это нужно. Также ошибка 504 может возникать, когда Nginx используется в качестве прокси для Apache или любого другого веб-сервера, тогда нужно еще настроить время ожидания для прокси. Добавьте эти строки в секцию server:

proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;

Тут уже мы задаем таймаут 600 секунд для различных видов действий — подключения, отправки данных, чтения данных и так далее. После завершения настройки Nginx стоит перезапустить:

sudo systemctl restart nginx

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

fgrep -i » 504 » /var/log/nginx/access.log

Более подробную информацию иногда можно увидеть в error.log:

fgrep -i » 504 » /var/log/nginx/error.log

Дальше, если проблема именно в php-fpm, вы можете отследить какие скрипты выполняются медленно с помощью встроенной функции slow-log. Для ее активации добавьте следующие строки в конфигурацию вашего пула:

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

slowlog = /var/log/php-fpm/www-slow.log
request_slowlog_timeout = 5s

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

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

Выводы

В этой статье мы рассмотрели как исправить 504 gateway time out Nginx 1.2 7, а также почему может возникнуть эта ошибка. Надеюсь, эта информация была полезной для вас.

Источник

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

Источник

Понравилась статья? Поделить с друзьями:
  • Ошибка 504 lada granta
  • Ошибка 5100 canon mx300
  • Ошибка 5022 мерседес w164
  • Ошибка 504 gateway time out тор браузер
  • Ошибка 510 http