Ошибка 504 gateway time out 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, а также почему может возникнуть эта ошибка. Надеюсь, эта информация была полезной для вас.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Creative Commons License

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

Об авторе

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

Код ошибки в формате 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.

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 Gateway Time-out Nginx

При попытке зайти на сайт Вы получаете сообщение ошибка 504 с текстом «Gateway Time-out. Nginx«. Такое сообщение появляется, как правило, на тех сайтах, где веб-сервер Nginx работает как фронт-энд для сервера Apache. Что это значит?
Несмотря на то, что ошибка 504 выдаётся именно Nginx, причиной появления её он не является, а сообщает нам о том, что долго ждал ответа от Апача, но так его и не дождался. Обычно такое происходит в тех случаях, когда на сервере, где расположен сайт, очень высокая нагрузка и он не успевает обрабатывать все HTTP-запросы. Как это устранить? 

Если Вы посетитель сайта. В там случае у Вас только один выход — ждать пока администрация веб-ресурса решит проблему у себя. Вы, как простой посетитель, ничего сделать не сможете. Просто с некоторой периодичностью (раз в 2-3 часа) просто пробуйте зайти на страничку. Чаше не надо! Коли там действительно превышена нагрузка, то вы будете только «подливать масло в огонь».
В тех случаях, когда надо срочно посмотреть содержимое странички, а она пишет «Error 504 Gateway Time-out» — можно воспользоваться кешированной версией, которая храниться в веб-кеше крупных поисковых сервисов — Яндекс и Гугл. Для этого достаточно ввести адрес страницы в строку поиска и в найденном результате выбрать вариант «Сохранённая копия».

Если Вы администратор сайта. В этом случае возможны два варианта:
а) Вы арендуете VPS/VDS и имеете SSH-доступ к нему.
Начните с перезапуска серверов. Я покажу на примере Fedora/CentOS. Сначала рестартим Апач:

service httpd restart

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

service nginx restart

Не помогло? Тогда можно попробовать увеличить таймаут. Для этого в nginx.conf прописываем параметр:

keepalive_timeout 60

По умолчанию его значение — 0.
Снова перезапускаем веб-сервер и смотрим изменилась ли ситуация.
Такой ход иногда может помочь. Но если на ресурс очень сильная нагрузка, то увеличив таймаут вы увеличите и количество ожидающих http-соединенний, а значит ещё повысите нагрузку, что крайне не желательно! А то плюсом добавится ещё и ошибка 502 Bad Gateway из-за перегруза httpd запросами.
Поэтому надо разобраться с тем, что же создаёт такую сильную нагрузку. Для этого воспользуемся командой:

top -c

Обратите внимание на значения в строчке «load average».

load average

Его максимальное значение должно быть не более количества ядер у процессора. Ну плюс/минус 2. Если значение более 10 — надо бить тревогу. Обычно такое возникает в случае DDOS-атаки, из-за которой Apache забит Sync-запросами. Ишите с помощью команды netstat IP-адреса ботов и заносите их в DROP-правила пакетного фильтра Firewall.
Если на Вашем ресурсе Nginx работает вместе с PHP-FPM, то очень часто ошибка 504 возникает из-за медленных скриптов. Веб-сервер просто не дожидается результата выполнения. Спаси может помочь добавление параметра

fastcgi_read_timeout 300;

в раздел:

location ~ .php$ {
....
}

б) Вы арендуете только хостинг без доступа к его настройкам.
При таком раскладе самостоятельно ничего сделать Вы не сможете и остаётся только обращаться в техподдержку Вашего хостинг-провайдера с просьбой устранить ошибку 504 Gateway Time-out. Обычно системные администраторы хостера помогают пользователям найти источник проблемы и устранить его. Если же они пошлют Ваш куда подальше, то выход будет только один единственный — менять хостинг-провайдера.

The 504 Gateway Timeout error is one of the most common HTTP 5xx errors faced by website owners and site visitors. For many blogs and ecommerce platforms, knowing how to fix server errors like this is crucial to keep their hard-earned visitors from bouncing to competitor sites.

As the 504 Gateway Timeout error doesn’t tell you why it occurred, it’s hard to pinpoint what’s causing the server timeout. This article will help you understand it in detail, learn how to diagnose its cause, and then fix it.

After trying all the various solutions mentioned in the post, your site should be up and running in no time.

Sound interesting? Let’s dive in!

Check Out Our Video Guide To Fixing the 504 Gateway Timeout Error on Your Site

The 504 Gateway Timeout error is one of the most common HTTP 5xx errors faced by website owners and site visitors. 🤔 Learn how to fix it with this guide quickly. ⬇️Click to Tweet

What Is the 504 Gateway Timeout Error?

The 504 Gateway Timeout Error indicates that the server didn’t receive a timely response from an upstream server it needed to access in order to complete a request. This can happen because the other server is not functioning properly, overloaded, or down.

To simplify it further, this error occurs when two servers are involved in processing a request. The first server (typically the main server) times out, waiting for a response from the second server (upstream server).

Error Code 504 Gateway Timeout Error
Error Type Server-side
Error Variations 504 Gateway Timeout504 Gateway Timeout NGINX
NGINX 504 Gateway Timeout
Gateway Timeout Error
Error 504
HTTP Error 504
HTTP Error 504 — Gateway Timeout
HTTP 504
504 Error
Gateway Timeout (504)
Error Causes Server connectivity issues
Network connectivity problems
DNS issues
Firewall issues

This is how the process works: every time you visit a website in your browser, the browser sends a request to the web server where the site is hosted. The server processes the request and responds with the requested resources.

Illustration of how HTTP requests and responses work

How HTTP requests and responses work.

The server response includes one of many HTTP status codes to indicate the response’s status to the browser. But not all these HTTP status codes are errors. For instance, a 200 OK status code means that the server processed the request successfully and “Everything is OK.”

The 5xx class of HTTP status codes indicates that something’s wrong with the server, the server is aware of it, and it cannot carry out the client request. As a result, they’re also referred to as Server Error 5xx status codes.

Officially, five status codes are specified under the 5xx class (500, 501, 502, 503, 504). You may come upon many unofficial codes too (506, 507, 509, 520, etc.).

The 504 Gateway Timeout error manifests itself in various forms. Here are some ways it usually shows up:

The HTTP ERROR 504 in Chrome browser

The ‘HTTP ERROR 504’ in the Chrome browser.

The 504 Gateway Timeout error is similar to the 502 Bad Gateway error, which indicates that the first server received an invalid response from the second server (upstream server).

504 GATEWAY TIMEOUT status code in Chrome DevTools

The ‘504 GATEWAY TIMEOUT’ status code in Chrome DevTools.

Variations of the 504 Gateway Timeout Error

The browser displays any 504 Gateway Timeout error inside it, just like any other error. As there are various operating systems, web servers, browsers, and user agents, it can show up in multiple ways.

Below are a few common 504 error message variations that you may run into:

  • 504 Gateway Timeout
  • 504 Gateway Timeout NGINX
  • NGINX 504 Gateway Timeout
  • Gateway Timeout Error
  • Error 504
  • HTTP Error 504
  • HTTP Error 504 — Gateway Timeout
  • HTTP 504
  • 504 Error
  • Gateway Timeout (504)
  • This page isn’t working — Domain took too long to respond
  • 504 Gateway Time-out — The server didn’t respond in time
  • The page request was canceled because it took too long to complete
  • Site visitors: There was an issue serving your request, please try again in a few minutes.
  • Site Owners: There was a gateway timeout. You should visit your error log for more information.
  • A blank white screen

All the above error responses, though worded differently, point to the same 504 Gateway Timeout server error.

Web servers and websites can customize how they show the 504 Gateway Timeout error to users. Some of them can be cool! It’s an excellent tactic to quell their visitors’ disappointment.

GitHub’s customized HTTP 504 error page

GitHub’s customized HTTP 504 error page.

What Are the Causes of the 504 Gateway Timeout Error?

As the 504 error is due to a timeout between servers, the problem probably isn’t with the client’s device or internet connection. That also includes your device and connection.

A 504 Gateway Timeout error indicates that the web server is waiting too long to respond from another server and “timing out.” There can be many reasons for this timeout: the other server is not functioning properly, overloaded, or down.

The other server need not always be external (e.g. CDN, API gateway). It can also be a server-like entity within the main web server (e.g. reverse proxy server, database server).

SEO Impact of the 504 Gateway Timeout Error

All 5xx errors prevent a webpage from loading, making them detrimental to user experience. Hence, search engines like Google take these errors seriously. If the error persists for a long duration, it may even lead to deindexing the webpage from the search engine results.

For example, when Google spiders stumble upon a 503 Service Unavailable error, they’ll understand that it’s a temporary issue as it’s mostly used to enable site maintenance mode. Thus, they’ll try to crawl the page again later.

A 504 Gateway Timeout error isn’t necessarily temporary as it can be due to multiple reasons. If your site is down for just a few minutes, and if the spiders are trying to crawl it multiple times every minute, they’ll try to serve the page from their cache.  They wouldn’t even notice it.

But if your site is down for 6+ hours or more, then Google will consider the 504 error as a serious site-wide issue that you need to fix as soon as possible. This can impact your SEO negatively.

Viewing the crawl errors in Google Search Console

Viewing the crawl errors in Google Search Console

Google Search Console is one of the best SEO tools to monitor your website’s HTTP 5xx errors.

How to Fix the 504 Gateway Timeout Error?

Without knowing exact details about the site, such as its server configuration, hosting plan, third-party plugins, and the traffic it attracts, you may find it frustrating and overwhelming to fix a 504 Gateway Timeout error.

Since many variables are involved, I recommend you to start by fixing client-side issues, which are pretty rare, and then move towards fixing server-side problems. They’re usually the culprits with 504 errors.

1. Try Reloading the Webpage

One of the first things you can try when encountering a 504 Gateway Timeout error is to wait a few minutes and try reloading the page.

You can press the F5 keyboard shortcut to refresh/reload the webpage in most browsers. To remove the page’s browser cache before reloading, you can press the CTRL+F5 shortcut combo instead.

Refreshing a webpage in Chrome browser

Refreshing a webpage in Chrome browser

While you’re at it, you can also try loading the site in a different browser to rule that out as an issue. As most 504 errors are due to temporarily overloaded servers, using this solution should make your site come right back.

If waiting and reloading the site doesn’t fix the 504 error issue, you can check whether a site is down for everyone or just you. Two useful online tools to test a site for downtime are Down for Everyone or Just Me and Is It Down Right Now?

Testing Kinsta.com on Down for Everyone or Just Me

Testing Kinsta.com on Down for Everyone or Just Me

2. Reboot Your Network Devices

Sometimes, problems with your network devices like modem or router could lead to a 504 Gateway Timeout error. Rebooting these devices could help you with fixing the problem.

While you can switch off all these networking devices in any order, the order you switch them back on is important. Typically, turn these devices on from the “outside-in,” following the connection order from the internet service provider to your main client device.

3. Check Your Proxy Settings

A proxy server sits between your device and the internet. It’s mostly used to enhance online privacy by hiding private information (e.g. device location) from websites and webservers (e.g. using a VPN).

While it’s rare for proxy servers to cause a 504 error, incorrect proxy server settings can sometimes be the reason. You can disable the proxy server and try reloading the webpage to see whether it’ll fix the error.

Changing the ‘Proxy’ settings in Windows 10

Changing the ‘Proxy’ settings in Windows 10

Most clients don’t use a proxy service, so you can skip this step if you’re confident that you don’t use any proxy server. However, you might have set it without you even knowing about it. I’d suggest you check your device’s and browser’s proxy settings to rule this cause out.

4. Check for DNS Issues

A 504 Gateway Timeout error can also be caused by DNS issues on the server-side or the client-side (or both).

The most probable reason for a server-side DNS issue is the FQDN (fully qualified domain name) not resolving the correct IP address or the DNS server not responding. Usually, this occurs when you’ve just migrated your site to a new server or host. Hence, it’s important to wait for the domain’s DNS records to propagate fully, which can take up to 24 hours.

You can use free tools like whatsmydns.net DNS Checker or DNSMap to see if your DNS has propagated around the globe.

Checking DNS propagation for your domain on whatsmydns.net

Checking DNS propagation for your domain on whatsmydns.net

For fixing client-side DNS issues, you could try flushing your local DNS cache. It’s like clearing your browser cache, except here, you’re flushing the DNS cache from the operating system.

If you’re using Windows, you can flush the DNS cache by opening the Command Prompt and entering the following directive:

ipconfig /flushdns

Flushing the DNS Cache with Command Prompt

Flushing the DNS Cache with Command Prompt in Windows

You should see a “Successfully flushed the DNS resolver Cache.” message if it worked.

For the latest macOS versions, you can open the Terminal and run the following command:

sudo killall -HUP mDNSResponder

You won’t see any notification in macOS when the process finishes, but you can change that by appending the command with your custom message.

sudo killall -HUP mDNSResponder; DNS Cache was cleared successfully

If you’re using older macOS versions, the command you need to enter varies based on which version of macOS you’re running. For more details, you can refer to the macOS section in Kinsta’s in-depth flush DNS tutorial.

If you’re using the Linux operating system, then the process is quite similar to macOS as even Linux uses the Terminal as its command-line interface. Since there are many Linux distributions, the exact command you need to run may vary from one distro to another. You can check out Kinsta’s guide for more information.

Finally, you can change your client-side DNS servers temporarily. By default, your ISP assigns the DNS servers automatically to you. But you can change these to public DNS IPs temporarily.

Some reliable DNS servers you can try out are Google Public DNS, Cloudflare 1.1.1.1, Quad9 DNS, and Cisco OpenDNS.

Settings custom DNS servers in Windows 10

Settings custom DNS servers in Windows 10

5. Disable Your Site’s CDN Temporarily

Sometimes, the issue could also be with your content delivery network (CDN). If a site’s origin server isn’t reachable, most CDNs will try to serve the full webpage from their cache.

But most CDNs don’t enable this feature by default as it’s complex to cache dynamic assets on most sites (e.g. the WordPress admin dashboard).

Setting the ‘Cache Everything’ page rule in Cloudflare

Setting the ‘Cache Everything’ page rule in Cloudflare

A straightforward way to troubleshoot this is to disable your CDN temporarily. For example, if you’re using the free CDN Enabler WordPress plugin to link your site assets to the CDN URLs, then you can deactivate the plugin and test reloading your site.

The same goes for using any other plugin you may use to connect to your CDN (e.g. WP Rocket, Breeze, W3 Total Cache).

If you can’t access your site’s admin dashboard, you can disable the plugin via SFTP by renaming the plugin’s folder name.

Disable all plugins via SFTP by renaming the plugins folder name

Disable all plugins via SFTP by renaming the plugins folder name

CDNs like Cloudflare or Sucuri, which provide full proxy services, have extra firewalls between their edge servers and your origin server. Hence, you may encounter HTTP 5xx errors more frequently while using them. Most of them cache 5xx errors returned by your origin server, so it’s easy to troubleshoot them.

Cloudflare’s free plan is prone to throw up a 5xx error. Unfortunately, since it’s a full proxy service, there’s no quick way to disable it. But before you blame Cloudflare for it, know that Cloudflare shows two variations of the 504 Gateway Timeout error.

504 Gateway Timeout at Cloudflare (Variation 1)

Cloudflare will show you a custom 504 Gateway Timeout error screen when your site’s origin server responds with a standard HTTP 504 response.

Cloudflare’s custom Error 504 screen

Cloudflare’s custom Error 504 screen

Here, the issue lies with your web server and not Cloudflare. You can try fixing it with the other solutions mentioned below or contact your hosting provider’s support for technical help.

504 Gateway Timeout at Cloudflare (Variation 2)

If Cloudflare causes the 504 Gateway Timeout error, the error screen will mention “cloudflare,” which is currently the standard server name for all Cloudflare assets. Usually, the error screen will appear as below:

504 Gateway Timeout error caused by Cloudflare

Error screen for 504 Gateway Timeout caused by Cloudflare

Since Cloudflare itself is unresponsive, you’ll not see any Cloudflare-branded error screen here.

Most likely, Cloudflare is already aware of the issue and is working on a fix already. You can confirm this by checking the Cloudflare System Status webpage. Alternatively, you can get in touch with Cloudflare support for a quicker resolution.

Check Cloudflare System Status at cloudflarestatus.com

Check Cloudflare System Status at cloudflarestatus.com

504 Gateway Timeout at Cloudflare Due to Large Uploads

The size of your uploads to your site can also be a reason for the server timeouts. Cloudflare limits upload file size (per HTTP POST request) to just 100 MB on both Free and Pro plans.

Cloudflare’s ‘Maximum Upload Size’ limits for various plans

Cloudflare’s ‘Maximum Upload Size’ limits for various plans

The issue can be on your host’s end or with Cloudflare. You can find out the exact cause by bypassing Cloudflare with your DNS hosts file and trying your upload again.

If you’re using Cloudflare with WordPress, I recommend using their free plugin and excluding critical URLs from caching (such as the WordPress admin dashboard). You can refer to Kinsta’s detailed post on how to configure Cloudflare settings for WordPress.

Suggested reading: How to Set up Cloudflare APO for WordPress.

6. Check Server Issues With Your Host

Server issues are one of the most common reasons for facing a 504 Gateway Timeout error. Since most WordPress sites are hosted on Nginx or Apache webservers, Nginx or Apache is waiting for a response from something and timing out.

Many clients come to Kinsta for exactly this problem they’re facing at other hosts. The conversation goes something like this:

We’re getting around 100k visitors per month with more than 200k views. Currently, we’re hosting with ____ and we experience 504 errors constantly due to server overload. I don’t like how ____ handled the problem, and we were also advised that we will have to move to their dedicated plans soon, which I believe is not necessary.

High-traffic and ecommerce sites are more prone to getting 504 errors because of server overload as they generate many uncacheable requests. However, this issue can crop with any site, including simple blogs. Many hosts will ask you to upgrade to a high-tier plan to fix the issue, which in most cases is unnecessary.

Kinsta uses LXD managed hosts and orchestrated LXC software containers for each site. Thus, every site is housed in its own isolated container with access to all the software required to run it (Linux, Nginx, PHP, MySQL). The resources are 100% private and aren’t shared with any other site, even your sites.

Most hosts providing shared hosting plans don’t have this capability. Hence, a high-traffic site hosted on the same server as yours may cause your site to throw up a 504 error too.

Apart from isolating each site in its container, Kinsta has also designed its infrastructure to handle thousands of concurrent connections easily. Kinsta even hosts the MySQL databases at localhost, not a remote server. This means no latency between machines, resulting in faster queries and fewer chances of timeouts occurring.

Many clients who migrate to Kinsta see huge decreases in overall load times.

A 212.5% increase in performance after switching to C2.

A 212.5% increase in performance after switching to C2.

An overloaded server isn’t the only cause for a server timeout. There can be many other reasons for the 504 error:

Slow Server Infrastructure

The server you use to host your site may not have enough resources to handle the load. It’s like playing a modern, graphics-intensive videogame on a decade-old PC.

The server just hangs up trying to serve the website. The only solution to this problem is to upgrade to a server with better infrastructure. For this reason, even Kinsta’s most basic hosting plan will handle a static site with medium traffic.

Needs More PHP Workers

PHP workers are used to execute your site’s code. An ecommerce site that gets 50,000 visitors per month needs a lot more resources than a simple blog with the same amount of traffic. If all the server’s PHP workers are busy, they’ll build up a queue.

When the queue gets too big, the server disregards old requests, which may cause the server to throw up a 504 gateway error. You can ask your host about increasing your number of PHP workers. This’ll allow your site to execute multiple requests simultaneously.

Firewall Issues

Your server’s firewall could have some errors or an improper configuration. Perhaps, a few of its rules prevent the server from establishing a connection properly. To know if your firewall is the culprit, you can check your server’s error logs.

Network Connectivity Problems

Connectivity issues between the proxy server and the web server could cause delays in responding to HTTP requests. If you use a load balancer, there could also be network connectivity issues with it.

HTTP Timeouts

HTTP timeouts can occur when a connection between the web server and the client is kept open for too long. With WordPress sites, this usually happens when running WordPress imports. One way to resolve this issue is to switch to a faster internet connection.

You can also use a tool with support for WP-CLI to run the scripts directly on the server, bypassing the HTTP connection entirely. For instance, you can use the wp import WP-CLI command to run the WordPress Importer plugin directly through the command-line interface.

Important: 504 Gateway Timeout errors look similar to 503 Service Unavailable errors or 502 Bad Gateway errors. But they’re all different. If you’re experiencing a 504 error at Kinsta, open a support ticket to get your issue fixed immediately.

For monitoring your site’s downtime on your own, you can use a tool like updown.io. It’ll check your website’s status (or any URL) periodically by sending an HTTP request to it. You can set the check frequency from 15 seconds to 1 hour. If your website isn’t responding correctly, it’ll notify you with an email or an SMS.

Monitor your website with updown.io

Monitor your website easily with updown.io

You’ll get a generous quantity of free credits with every account of updown.io, but if you’re looking for cheaper alternatives, you can check out WebGazer or UptimeRobot. Both these tools will help you monitor your site’s uptime every 5 minutes for free. That’s decent enough for most website owners.

WebGazer website monitoring tool's dashboard

WebGazer website monitoring tool’s dashboard

Monitoring your website will give you an idea of how often it’s down. This is especially helpful if you’re using a shared hosting provider. Most application, database, and managed WordPress hosts (like Kinsta) take care of this automatically for you. Hence it’s always recommended to go with them.

For a detailed explanation, check out Kinsta’s post on the importance of managed WordPress hosting.

7. Check for Spam, Bots, or DDoS Attacks

Malicious attackers can bring your web server to a crawl by sending too many and/or resource-intensive requests. If your site is getting spammed by bots or undergoing a DDoS attack, it can overwhelm your server and result in 504 Gateway Timeout errors for many genuine users.

You can look at your server traffic and analytics to see if you can spot any irregular patterns in the site traffic. If you’re using Kinsta to host your site, you can view this data easily by going to your MyKinsta Analytics dashboard.

Screenshot: Site-level Analytics in MyKinsta.

Site-level Analytics in MyKinsta.

Start your investigation by looking at the top client IPs. It’ll give you an idea of who generates the maximum number of requests, and from where. If your server suddenly uses up enormous bandwidth or attracts a lot of traffic, then this report will come in super handy.

Screenshot: Top client IPs displayed in MyKinsta Analytics dashboard.

Top client IPs displayed in Analytics dashboard.

Next, you can check out the Cache Analysis report. Here, you can see how many requests are bypassing or missing the cache, or being served from the cache. For performance and stability reasons, you want to cache as many requests as possible, but it’s not always possible to achieve that.

For example, WooCommerce sites generate many uncacheable requests for features such as the shopping cart and the checkout process.

The ‘Cache Analysis’ screen in MyKinsta

The ‘Cache Analysis’ screen in MyKinsta

Finally, you can use a security plugin to beef up your website’s security by spotting and blocking worrisome traffic/IPs. You can ask your host to block certain IPs too.

Depending upon the length and scale of the attack, this could be a never-ending process of blacklisting IPs as many attackers change their IPs and proxy addresses after getting blocked.

Note: Kinsta doesn’t allow its clients to install security plugins as they can have a huge effect on the site’s performance, especially its scanning capabilities. As Kinsta uses load balancers with Google Cloud Platform, blocking IPs wouldn’t always work as intended.

You can use dedicated security solutions such as Cloudflare or Sucuri to protect your sites from DDoS attacks and spambots. For more, you can check out Kinsta’s articles on how to install Cloudflare on your site and how Sucuri helped stop a DDoS attack in its tracks.

8. Repair Your Corrupted WordPress Database

Sometimes, a 504 Gateway Timeout error can be because of a corrupt database, especially in WordPress sites. Typically, this is due to corrupted database tables or files. Sometimes, it can also be caused by a serious security issue like your site or database being hacked.

Repairing a corrupted WordPress database depends on the problem. Plugins like WP-DBManager make it easy to diagnose database issues and repair them. I recommend you to read Kinsta’s detailed walkthrough on repairing WordPress database issues to get started.

9. Check Your Site’s Plugins and Themes

In most cases, third-party plugins and themes don’t cause 504 errors. But there’s a slight chance that they might cause server timeouts, usually by queuing up many uncached requests generated by the plugin/theme. As this ties up a lot of your server’s PHP workers, it can cause 504 errors.

A great example of this issue is WooCommerce, a plugin installed to add ecommerce functionality to WordPress sites.

The simplest way you can troubleshoot this problem is by deactivating all your plugins. Remember, you won’t lose any data if you just deactivate a plugin.

If you can access your admin dashboard, you can go to the Plugins screen, select Deactivate from the bulk actions menu, checkmark all the plugins, and then hit the Apply button. This will disable all of your plugins.

Deactivate plugins in WordPress

Deactivating all the WordPress plugins through WP admin dashboard

If you can’t access your admin area, you can disable plugins via SFTP using the method described before. Just rename the main plugin folder name to disable all the plugins in bulk.

Once you’ve deactivated all the plugins, check whether your site loads properly. If it works, you must activate each plugin, testing the site after enabling every plugin.

Finally, make sure that your plugins, themes, and WordPress core are up to date. Also, ensure that your server is running the recommended version of PHP.

If you feel this to be too overwhelming, you can always reach out to your host for help. Kinsta uses Kinsta APM and other troubleshooting techniques to help clients narrow down what plugin, query, or script might cause the error.

In the worst-case scenarios, like an inefficient query or bad code in a plugin/theme, you can bring in a WordPress developer to fix the issue.

10. Check Error Logs

Viewing error logs can be very helpful when troubleshooting and debugging 504 errors on your site. This can help you narrow down an issue on your site quickly, especially if it’s resulting from a demanding plugin on your site.

If you’re a Kinsta customer, you can easily see logged errors in the MyKinsta dashboard. Start by selecting WordPress Sites in the sidebar menu, choose the site you want to examine, then select Logs to open the Log viewer page.

Screenshot: Viewing the error log within the MyKinsta dashboard.

Viewing the error.log file within the MyKinsta dashboard.

If your host doesn’t have a logging tool, then you can enable WordPress debug mode by adding the following code to your wp-config.php file:

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );

The WP_DEBUG constant enables or disables the WordPress debug mode. It has two optional companion constants that can extend its features. The WP_DEBUG_LOG constant directs all errors to be saved to a debug.log file within the /wp-content/ directory. If you don’t see this file, you can always create one.

The WP_DEBUG_DISPLAY constant controls whether debug logs show up on the HTML page. Setting this to false will hide all errors, but you can review the errors later, as you’ve also defined WP_DEBUG_LOG as true.

Important: If you have WP_DEBUG enabled in the Kinsta environment, it’ll route all errors to the debug.log file and not the error.log in the MyKinsta dashboard.

You can also download the raw WordPress error log files via SFTP. Typically, you can find error logs in your server’s root directory in a folder named “logs.”

Accessing the WordPress error logs folder via SFTP

Accessing the WordPress error logs folder via SFTP

Kinsta users can also enable WordPress debug mode from their MyKinsta dashboard. To do that, navigate to Sites > Tools > WordPress Debugging and click the Enable button. This will allow you to see PHP errors and notices without enabling debug mode via SSH or SFTP.

Lastly, you can check the server log files. Depending on which server you’re using to host your WordPress site, they’re commonly found in these locations:

  • Apache: /var/log/apache2/error.log/
  • Nginx: /var/log/nginx/error.log/

You can refer to logging related documentation of Apache or Nginx for more information.

11. Configure Apache or Nginx Settings Properly

You can edit your server config files to increase resource limits for specific directives. This can help you resolve the 504 Gateway Timeout error.

For Apache Webservers

First, add the following code to your httpd.conf:

TimeOut 600

This setting defines how long the server will wait for certain requests before marking it as a network timeout issue. Its default value is 60 seconds (Apache 2.4 version).

You can only add this directive in your httpd.conf file, not in your .htaccess file. Since most shared hosting providers don’t allow you to modify the httpd.conf file, you can try increasing the value of the LimitRequestBody directive in your .htaccess file instead.

Then add the following line to your php.ini file:

max_execution_time 300

The default value of PHP’s max_execution_time directive is 30 seconds. Increasing it will allow your site’s PHP scripts to run longer.

For Nginx Webservers

If you’re running your WordPress sites on Nginx + FastCGI Process Manager (PHP-FPM) or using Nginx as a reverse proxy for Apache, you can tweak the server settings to help prevent 504 Gateway Timeout errors.

504 Gateway Timeout Error on Nginx + FastCGI (PHP-FPM)

First, you must edit your PHP-FPM pool config file. You can find it at the /etc/php7.4/fpm/pool.d/www.conf location in your Nginx server (the exact path may vary based on the PHP version). Alternately, you can run the following command in your terminal to edit the PHP-FPM pool config file:

sudo nano /etc/php/7.2/fpm/pool.d/www.conf

Next, set the following directive:

request_terminate_timeout = 300

After this, you must edit your php.ini file. You can locate it at /etc/php.ini. Open the file and add/change the value for the max_execution_time directive to 300 seconds.

max_execution_time = 300

Finally, add the following code to your nginx.conf file’s location block:

location ~ .php$ {
...
fastcgi_read_timeout 300;
}

Reload Nginx and PHP-FPM for the changes to take effect.

sudo service nginx reload
sudo service php7.4-fpm reload

The exact code to reload PHP-FPM will vary based on the PHP version installed on your server. Test your site to see whether it has fixed the issue.

504 Gateway Timeout Error on Nginx Proxy

If you’re using Nginx as a reverse proxy server for Apache, then you can make it more lenient towards server timeouts by adding the following directives to your nginx.conf file:

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

Don’t forget to reload Nginx after making your changes.

sudo service nginx reload

Other HTTP Errors Like 504 Gateway Timeout

As mentioned earlier in the article, many other HTTP 5xx errors are just like the 504 Gateway Timeout error. It’s because they all happen on the server-side. These errors include:

  • 500 Internal Server Error
  • 501 Not Implemented Error
  • 502 Bad Gateway Error
  • 503 Service Unavailable Error

Other HTTP errors caused due to client-side issues, like the 404 Not Found error, are also like the 504 error. You can refer to Kinsta’s detailed guide and list of HTTP status codes for more information.

When you don’t know what caused a 504 Gateway Timeout error, how do you fix it in time to keep hard-earned visitors from bouncing to competitor sites? 🤷‍♂️ All the details are in this post. ⬆️Click to Tweet

Summary

Your site can be affected by the 504 Gateway Timeout error because of multiple reasons. In this article, you learned how to troubleshoot them all. Typically, these errors are caused due to server-side issues, in which case you can reach out to your host and get it resolved quickly.

However, you must also understand that this error can be due to third-party plugins, themes, services, inefficient database queries, or a combination of two or more of these. If you’re maxing out your server’s resources (e.g. PHP workers), it’s recommended to optimize your site for performance.

If you still find that your website is timing out, then it might very well be that you need to upgrade your hosting plan or the number of PHP workers. I recommend you to consider this option only after you’ve exhausted all the other solutions described in this article.

From simple static sites to complex ecommerce and membership sites, Kinsta’s scalable hosting plans are designed to accommodate all types of websites. To learn more about our scalable cloud hosting, check out this article on the most important things you should know about Kinsta!

Did we miss anything? If you’re still finding it difficult to fix the 504 Gateway Timeout error on your site, leave a comment below.

Ошибка 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 ошибка точно не будет появляться на сайте.

Users get 504 Gateway Timeout Error in NGINX when you use it as a reverse proxy server and it gets timed out waiting for a response from back end web servers. Here’s how to fix 504 Gateway Timeout error in NGINX.

When you use NGINX as reverse proxy server and it times out waiting for a response from back end web servers, it sends a 504 Gateway Timeout error to client browser. This can happen due to various reasons such as application bugs, faulty plugins, poorly configured modules. Sometimes, it may be due to network issues and may get fixed automatically.

Bonus Read : How to Fix 502 Bad Gateway Error in NGINX

How to Fix 504 Gateway Timeout Error in NGINX

Here are some of the key ways to fix 504 Gateway Timeout Error in NGINX.

1. Server goes down

One of the most common causes for 504 bad gateway is that your back end server has gone down because it got overloaded with too many requests, or some long running requests. Such issues get fixed automatically when server  load gets balanced. However, analyze server logs to identify the requested URLs just before your server went down, to optimize their code. Sometimes, it may also be a signal that you need to upgrade your server.

2. DNS issue

DNS issue can be on client side or server side. In case of server side DNS problems, the issue may be because your domain name doesn’t resolve to an IP, in case you have changed your website IP address or migrated your website to a new IP. In such cases, it may take anywhere between 5 minutes to 24 hours for the DNS records to be updated.

In case of client-side problems, try flushing local DNS cache.

Bonus Read : How to Increase Request Timeout in NGINX

3. Disable CDN

If your website uses CDN, it may sometimes timeout causing NGINX to return 504 Gateway Timeout error. In such cases, just disable your CDN and try accessing your website.

4. Network Connectivity

NGINX will also give 504 Gateway Timeout error if there are network connectivity issues between your reverse proxy server and back end web server. Log into your proxy server and try connecting to your web server using curl/ping command.

Bonus Read : How to Increase File Upload Size in NGINX

5. Firewall Issues

If your web server’s firewall is not properly configured it may block many requests causing NGINX to give 504 Gateway Timeout error.

6. Spams, Bots and DDOS attack

Sometimes malicious attackers may flood your web server with too many requests, or slow running requests. Monitor your server log to see if there is any spike in traffic, identify their IP address ranges and put measures in place to regulate their incoming requests.

Bonus Read : How to Hide NGINX Server Version From Header

7. Bugs and Faulty Plugins

Sometimes application bugs, faulty plugins and poorly configured modules can also slow down or bring down your server, causing NGINX to return 504 Gateway Timeout error. In this case too, you need to analyze server logs to find out which requested URLs are causing the issue and fix them soon.

Hopefully, the above tips will help you fix 504 Gateway Timeout Error in NGINX.

Ubiq makes it easy to visualize data in minutes, and monitor in real-time dashboards. Try it Today!

Related posts:

  • About Author

mm

Понравилась статья? Поделить с друзьями:
  • Ошибка 504 ddos
  • Ошибка 504 cloudflare
  • Ошибка 504 bad gateway что это значит
  • Ошибка 504 1с линк
  • Ошибка 503f indesign