Ошибка 502 bad gateway nginx как исправить

Опубликовано:

  • DevOps

502 Bad Gateway обычно возникает, когда Nginx работает, как обратный прокси-сервер и не может подключиться к серверным службам. Это может быть связано со сбоем службы, сетевыми ошибками, проблемами конфигурации и т.д. Рассмотрим пять основных причин возникновения этой ошибки и то, как их исправить.

Поддерживать сервер сложно.

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

Одной из таких распространённых ошибок на серверах Nginx является 502 Bad Gateway.

Nginx Ошибка 502 Bad Gateway

Сообщение об ошибке загадочно.

Итак, многие веб-мастера засучивают рукава и смотрят error.log:

2017/04/04 08:34:43 [error] 949#949: *7 connect() failed (111: Connection refused) while connecting to upstream, client: XXX.XXX.XXX.XXX, server: myserver.com, request: "GET /myurl-this/ HTTP/1.0", subrequest: "/redis-fetch", upstream: "redis://127.0.0.1:6379", host: "refserver.com", referrer: "http://referalsite.com/myurl-this/"

Да, ещё больше непонятного…

Вы понимаете, что что-то напутано, потому что он сообщает failed (сбой) и refused (отказ).

Но что это означает?

Вот решение. Мы перечислили пять основных причин возникновения ошибки Nginx 502 Bad Gateway и способы их решения.

Сбой серверной службы

Nginx зависит от серверных служб, таких как PHP-FPM, служб баз данных и серверов кэша для запуска веб-приложений.

Таким образом, если какой-либо из этих сервисов выйдет из строя или зависнет, Nginx не получит никаких данных, что приведёт к ошибке 502 Bad Gateway.

Службы, которые, как мы видели, сбоили — это:

  • PHP-FPM
  • Apache
  • Cache
  • Database

Причины сбоя службы могут варьироваться от всплесков трафика и ограничений ресурсов до ошибок диска и DDoS-атак.

Если вы подозреваете, что серверная служба не отвечает или вышла из строя, попробуйте завершить все не отвечающие процессы и перезапустить службу.

Например, вот один из способов убить нефункционирующие процессы PHP-FPM и перезапустить службу.

$ kill -9 $(pgrep php-fpm)
$ /etc/init.d/php-fpm restart
* Restarting PHP FastCGI Process Manager php-fpm [ OK ]

Внимание: Не запускайте эти команды, если не знаете, как они работают.

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

Высокая нагрузка на сервер

Вторая наиболее распространённая причина ошибки Nginx 502 Bad Gateway является высокая средняя загрузка серверов.

Всплески нагрузки приводят к тому, что службы не отвечают. Мы видели следующие причины скачков нагрузки:

  • Внезапный всплеск посещаемости сайта (может быть сезонным или маркетинговым/рекламным).
  • Заражение вредоносным программным обеспечением (вирусы/трояны/майнеры/сканеры и т.д.) на сервере.
  • Рассылка спама в комментариях или использование других уязвимостей.
  • Брут форс атаки на веб-приложения.
  • Ошибки приложений, вызывающие утечку памяти или перегрузку ресурсов.

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

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

Неправильная конфигурация сервиса

Сервер Nginx и серверные службы зависят от многих подсистем. Таких, как DNS resolver, процессы Apache, службы PHP, сервер базы данных и т.д. Если даже одна из этих служб имеет неправильную конфигурацию, эта служба не сможет ответить, и Nginx покажет ошибку 502 Bad Gateway.

Проблемы с конфигурацией, с которой мы сталкивались:

  • DNS resolver неправильно настроен в Nginx, что приводит к сбою поиска домена.
  • Данные логина БД настроены неправильно после недавней миграции, восстановления или обновления.
  • Синтаксическая ошибка настроек брандмауэра Apache (mod-security), вызывающая сбой Apache.
  • Для приложений PHP установлены неправильные ограничения памяти или файлов.
  • Ограничения пропускной способности (например, количество подключений на IP-адрес) установлены слишком строго, что приводит к сбою легальных посетителей.
  • …и многое другое.

Не существует простого способа обнаружения ошибки конфигурации. Вам нужно просмотреть error.log и обратить внимание на то, что написано об ошибке.

Например, эта ошибка сообщает, что приложение PHP достигло максимально допустимого предела процессов (определяемого параметром pm.max_children).

WARNING: [mysite.com] server reached max_children setting (30), consider raising it
ERROR: unable to read what child say: Bad file descriptor (9)

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

Порт сервиса заблокирован в брандмауэре

Брандмауэры/файрволлы — основа безопасности сервера. Но если их неправильно настроить, это может привести к блокировке запросов или сбою служб.

Например, на серверах Linux, на которых работает пакет автоматизации Plesk, Nginx работает на 80 порту, а Apache на 7080. Но брандмауэры/файрволлы по умолчанию блокируют необычные порты, и это приведёт к том, что Nginx не сможет подключиться к Apache.

Результат? Ошибка 502 Bad Gateway.

Такие проблемы часто возникают при включении новой службы (например, кэширующий сервис, Ruby, и т.д.) в бэкенде, во время миграции или после обновления сервера.

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

$ netstat -lpn
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 19785/nginx
tcp6 0 0 :::80 :::* LISTEN 19785/nginx

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

Ошибки веб-приложений

Редким случаем ошибки 502 Bad Gateway является ошибка приложения.

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

[notice] child pid 27831 exit signal Segmentation fault (11)

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

Итог

Ошибка 502 Bad Gateway в Nginx обычно возникает, когда Nginx работает как обратный прокси и не может подключиться к серверным службам. Это может быть связано со сбоями службы, сетевыми ошибками, проблемами конфигурации и т.д. Мы рассмотрели пять основных причин этой ошибки и способы её устранения.

Загружая страницу, браузер отправляет кучу запросов другим серверам. Они обрабатывают все запросы, затем возвращают код ответа HTTP с определенным результатом. Если в процессе этого возникнет какой-то сбой, на экране браузера отобразится ошибка. И одна из таких ошибок – 502 Bad Gateway. Я расскажу, что она означает, по каким причинам выходит, а еще опишу способы ее устранения.

Что означает ошибка 502 Bad Gateway

Ошибки, принадлежащие серии 5xx, означают появление проблем на стороне сервера. Если взять конкретно ошибку 502 Bad Gateway, то ее появление будет означать получение неправильного ответа сервера. «Виновниками» в такой ситуации обычно являются прокси, DNS или хостинг-серверы.

Причины возникновения ошибки

Наличие ошибки 502 Bad Gateway может быть связано с несколькими причинами. Рассмотрим наиболее встречаемые: 

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

  • Сетевые проблемы. Ошибка 502 может возникать из-за проблем в сети – возможно, соединение было разорвано или возникли проблемы с маршрутизацией. Рекомендуется перезагрузить роутер, чтобы устранить ошибку. Если проблема сохраняется, то лучше связаться с интернет-провайдером для получения помощи.

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

  • Хакерская атака. Злоумышленники могут использовать DDoS-атаку на сайт в своих личных целях. Суть атаки в имитации большого наплыва пользователей – чересчур высокий поток может обеспечить возникновение кода 502.

  • Ошибки в коде сайта. Часто бывает и такое, что на сайте используется неправильно написанные функции и иные строчки кода, в результате чего появляется ошибка 502. Также это может быть связано с недавно загруженными плагинами или выходом из строя уже имеющихся.

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

Чем отличается ошибка 502 Bad Gateway Nginx

Если вы столкнулись с ошибкой 502, то она может идентифицироваться как Bad Gateway Nginx или Bad Gateway Apache. Отличий как таковых нет, разные названия лишь говорят о том, какой именно используется веб-сервер, который применяется для снижения нагрузки на сервер, аутентификации пользователей и многого другого. Именно он информирует о наличии кода 502, поэтому вы можете встретить в описании слова Nginx и Apache. Это наиболее популярные веб-серверы.

Комьюнити теперь в Телеграм

Подпишитесь и будьте в курсе последних IT-новостей

Подписаться

Что делать, если вы пользователь

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

Перезагрузить страницу

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

Проверить подключение к интернету

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

Очистить кэш и cookies

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

Для любого браузера актуально – зайти в историю просмотров и найти ссылку «Очистить историю». В новом окне отметить пункты с кэшем и cookies, затем подтвердить действие. Как только данные будут удалены, надо вновь попробовать загрузить страницу. Не помогло? Идем дальше!

Очистить кэш DNS

Допустимо, что в кэше установлено неправильное значение IP-адреса. Для таких случаев можно использовать сброс DNS кэша. В зависимости от операционной системы кэш DNS очищается по-разному. Давайте рассмотрим ниже, какие нужно выполнять действия под конкретную ОС. 

Windows

Очистка кэша на Windows выполняется через командную строку. Для этого необходимо сделать следующее:

1. Открываем меню Пуск и вводим запрос «Командная строка». В отобразившемся окне запускаем нужный инструмент.

Как открыть командную строку в Windows 10

2. Следующим шагом вводим запрос ipconfig /flushdns и ожидаем окончания работы приложения. Должна появиться надпись «DNS успешно очищен».  

Как очистить DNS-записи в Windows 10

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

Mac

В данном случае нужно будет воспользоваться терминалом: 

1. Используем комбинацию клавиш Command + Space, затем находим и открываем приложение «Терминал».  

Как в MacOS открыть командную строку

2. В отобразившимся окне вводим команду sudo killall -HUP mDNSResponder и ожидаем окончания работы инструмента. 

Linux

Здесь так же, как и на MacOS, нужно воспользоваться встроенным приложением «Терминал» – открываем его с помощью комбинации клавиш «Ctrl+Alt+T» и вводим необходимую команду. Она может отличаться в зависимости от типа операционной системы.

Для Ubuntu:

sudo service network-manager restart

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

sudo /etc/init.d/nscd restart

Попробовать зайти с другого браузера

Проблема 502 Bad Gateway может быть актуальна и для конкретного браузера. Если у вас на компьютере есть другой интернет-обозреватель, попробуйте открыть сайт через него. 

Отключить плагины и расширения

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

Зайти на страницу позже

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

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

Ошибка 400 Bad Request

Что такое ошибка 500 и когда она возникает

Что делать, если вы администратор сайта

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

Проверка журнала ошибок

Актуально в случаях, при которых ошибка 502 Bad Gateway появляется после внесения изменений или обновления. Определить это очень просто, нужно лишь проверить журнал ошибок. В CMS WordPress можно включить запись возникающих ошибок, добавив в файл wp-config.php вот такие строки:

define( 'WP_DEBUG', true );

define( 'WP_DEBUG_LOG', true );

define( 'WP_DEBUG_DISPLAY', false );

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

Проверка плагинов

Следует проверить, не влияют ли какие-либо плагины на работу сайта. Для этого можно поочередно отключать их, просто переименовывая папку интересующего плагина. Для этого надо выделить папку, затем нажать на меню «Файл» и в нем выбрать пункт «Переименовать».

Отключение плагина в WordPress путем переименования папки

Проверка сети CDN

Сети CDN и службы предотвращения DoS тоже могут влиять на работу сайта. Обычно виновник проблемы указывается на странице с кодом ошибки. Например, если под кодом 502 Bad Gateway есть строка cloudflare-nginx, значит, для исправления ошибки надо обратиться в службу поддержки CloudFlare. Можно отключить данный сервис, но потом придется долго ждать обновления DNS (это может занять несколько часов).

Один их вариантов отображения ошибки 502 Bad Gateway

Отключение anti-DDos

Отключение защиты от DDoS-атак может быть одной из возможных причин возникновения ошибки 502 Bad Gateway. Обычно анти-DDoS-системы используются для обнаружения и снижения воздействия DDoS-атак, которые направлены на веб-сервер. Однако иногда эти системы могут неправильно работать или применять слишком строгие фильтры, что может привести к блокировке допустимого трафика и, как результат, к ошибке 502.

Если вы столкнулись с подобными проблемами после отключения анти-DDoS-защиты, рекомендуется выполнить следующие действия:

  • Изучите конфигурацию anti-DDoS. Если у вас есть доступ к настройкам анти-DDoS-системы, проверьте их на предмет возможных проблем или ошибок. Убедитесь, что фильтры правильно настроены и не блокируют трафик.

  • Свяжитесь с провайдером услуг анти-DDoS. Расскажите о проблеме, которую вы испытываете, и попросите проверить конфигурацию системы или предоставить рекомендации по ее настройке.

  • Улучшите настройки анти-DDoS-системы. Обратитесь к документации или технической поддержке поставщика системы для получения инструкций по оптимальной конфигурации.

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

Увеличение количества ресурсов

Еще одной причиной появления ошибки 502 Bad Gateway может быть увеличение количества ресурсов сервера. Вот с чем можно столкнуться:

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

  • Недостаточная инфраструктура. Увеличение количества ресурсов может потребовать более мощной инфраструктуры, чтобы обрабатывать дополнительную нагрузку. Если сервер или сетевая инфраструктура не могут эффективно обслуживать увеличенное количество запросов или обрабатывать более высокую нагрузку, это может привести к ошибке 502.

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

  • Проблемы с базой данных. Проверьте настройки и производительность БД, а также убедитесь, что она способна обслуживать увеличенный объем данных и запросов.

Ошибка 502 на виртуальном хостинге VPS/VDS

Ошибка 502 Bad Gateway возникает из-за превышения лимита трафика пользователей, «шалостей» бота, скачивания сайта или даже DoS‑атаки. Решение данной проблемы кроется в ограничениях памяти.

Запустить команду top

Данный запрос в терминале поможет установить наличие свободной памяти. Этим же способом можно проверить, работает ли Apache.

Посмотреть логи Apache и nginx

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

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

Увеличить объем памяти

Бывает, что с логами все нормально, но памяти на обработку запросов все равно не хватает. Узнать об этом просто – при проверке командой top будет выдана ошибка OOM (out of memory). В таких случаях можно просто увеличить ее объем. Можно просто заказать другой тариф, в котором количество предоставляемой памяти больше. Подробнее об этом.

Проверить лимиты на php-cgi процессы

Если после проверки командой top показано, что свободной памяти еще достаточно, значит, на php-cgi процессы установлены лимиты. Для решения надо открыть конфигурационный файл Apache – httpd.conf, найти секцию модуля FastCGI (mod_fascgi или mod_fastcgid) и увеличить лимит.

Обратиться к службе технической поддержки

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

Влияние 502 на SEO

Ошибка 502 Bad Gateway – это временная проблема, когда сервер, выступая в роли шлюза или прокси, не может получить ответ от сервера, к которому он обращается. Несколько кратковременных ошибок 502 не должны существенно влиять на SEO, так как поисковые роботы обычно понимают, что это временное состояние. Однако частые и продолжительные ошибки могут негативно сказаться на SEO и привести к потере индексации страниц и плохому пользовательскому опыту. Чтобы минимизировать негативное влияние на SEO, рекомендуется проводить регулярный мониторинг веб-ресурса и оперативно решать проблемы, связанные с появлением ошибки 502.

502 Bad Gateway is an error website visitors see relatively rarely. However, since it can prevent the users from interacting with the website or the hosted application, website owners should make rectifying this error their top priority.

This error typically occurs when a server acting as a gateway or proxy receives an invalid response from an upstream server. Since NGINX is a popular proxy server, users often see error messages like “502 Bad Gateway” and the active NGINX version.

The NGINX 502 Bad Gateway is a common issue website visitors encounter. There are several possible causes for this error and several solutions. This post will examine the most likely reasons and how site owners and developers can resolve the error.

Let’s start with a short introduction to the error.

Table of Content

  1. What Does the Error Code 502 Bad Gateway in NGINX Mean?
  2. What is PHP-FPM & How Does It Work?
  3. The Top Six Possibilities Behind 502 Bad Gateway in NGINX (And How to Fix Them)
  4. Reason # 1: NGINX is Not Running
    1. Examine the NGINX Status
    2. Examine the NGINX Configuration
    3. Check the Port Bindings
    4. Check for Conflicting Services
    5. Examine the NGINX Error Logs
    6. Examine The System Resources
  5. Reason # 2: PHP-FPM Isn’t Working
    1. Examine the NGINX and PHP-FPM Configurations
    2. Check the Status of PHP-FPM
    3. Restart NGINX and PHP-FPM
    4. Examine the Socket or Address and Port Settings
    5. Examine PHP-FPM Error Logs
    6. Examine the File Permissions
    7. Test Configurations With a Simple PHP Script
  6. Reason # 3: The PHP-FPM Timeout Has Expired
    1. Increase the Value of the Timeout
    2. Restart PHP-FPM Service
    3. Improve Your PHP Code
    4. Check for Resource Constraints
  7. Reason # 4: NGINX Requests Denied by the Firewall
    1. Examine the Firewall Rules
    2. Temporarily Disable the Firewall
    3. Examine the Firewall Logs
    4. Allow NGINX Through the Firewall
    5. Test Connectivity
  8. Reason # 5: A Domain Name is Not Permitted
    1. Check the server_name Directive
    2. Examine DNS Resolution
  9. Reason # 6: Bugs In Web Applications
  10. Conclusion
  11. FAQs

What Does the Error Code 502 Bad Gateway in NGINX Mean?

502 Bad Gateway indicates that the server you are trying to reach has encountered an error while communicating with another server. This occurs when one server serves as a proxy to receive data from other servers in the setup. The 502 error occurs when a server returns an error when attempting to connect to another server.

The exciting aspect of this discussion is the several ways to indicate that a 502 error has occurred. Here’re a few ways you’ll find this error being mentioned on various websites:

  • 502 Bad Gateway NGINX
  • HTTP 502
  • HTTP Error 502 – Bad Gateway
  • 502 Service Temporarily Overloaded
  • Temporary Error (502)
  • 502 Bad Gateway
  • 502 Proxy Error
  • Error 502

As with the 404 Not Found error, developers can customize the appearance of the 502 error page to match the current website design.

Before going into the probable reasons for the 502 Bad Gateway error in NGINX, let’s discuss PHP-FPM and its role in NGINX performance.

What is PHP-FPM & How Does It Work?

PHP applications deployed on a server use PHP-FPM (PHP-FastCGI Process Manager) as a tool for handling web requests. When combined with NGINX, PHP-FPM can make websites run faster and use fewer resources for responding to requests.

If you use PHP-FPM, PHP works as a separate service, and the web requests are handled through a TCP/IP port. NGINX only handles HTTP requests in this configuration, while PHP-FPM reads PHP code. This arrangement ensures a faster response by distributing the workload over two services.

Now that you have a good idea about the 502 Bad Gateway error in NGINX, let’s discuss why this error occurs.

The Top Six Possibilities Behind 502 Bad Gateway in NGINX (And How to Fix Them)

Here’re the six reasons users might encounter the 502 Bad Gateway error.                                                                                                                           

502 bad gateway

Reason # 1: NGINX is Not Running

If you receive a “502 Bad Gateway” error, first, you should check whether NGINX is up and running. Here’s how you can debug this problem:

Examine the NGINX Status

Start by confirming that NGINX is up and operating. For this, launch the terminal and enter the following command:

$ sudo service nginx status or systemctl status nginx

nginx service status

As you can see, this command will display the NGINX web server’s current status. If it isn’t running, you’ll see a message saying that NGINX isn’t running.

If that’s the case, you can try restarting it with the following command that restarts NGINX and attempts to bind it to the designated ports:

$ sudo service nginx restart

Examine the NGINX Configuration

An error in the NGINX configuration file can likely stop it from functioning correctly. To verify this, use the following command to verify the configuration syntax:

$ sudo nginx -t

nginx syntax check

This command checks the NGINX configuration file for syntax issues. If there are any errors, it will specify the exact problem.

You can rectify the mistakes by editing the configuration file (/etc/nginx/nginx.conf or /etc/nginx/conf.d/*). If the syntax is okay, you will see a similar message:

nginx syntax ok

Check the Port Bindings

If NGINX is working correctly, you should next check that NGINX is bound to the adequately designated ports. NGINX listens on port 80 for HTTP and port 443 for HTTPS by default.

Open the NGINX configuration file (/etc/nginx/nginx.conf or /etc/nginx/conf.d/*) and look for the listen directives within the server blocks. Here you should check that the ports are correctly specified.

Check for Conflicting Services

If NGINX does not start because of port conflicts, the main reason is that another service may be already mapped to the same port. You can use the following command to identify any conflicting services:

$ sudo netstat -tuln | grep LISTEN

netstat connection check

This command displays all the services currently listening on specific ports. Look for any services that use ports 80 or 443. If you discover any conflicts, you must stop or adjust those services to free up ports for NGINX.

Examine the NGINX Error Logs

When investigating the 502 error, the NGINX logs can help determine what went wrong with the reverse proxy server. Typically, error logs are stored at /var/log/nginx/error.log. We recommend examining these log files for any error messages that may point to the source of the problem.

Examine The System Resources

Verifying that your server has sufficient resources (CPU, RAM, and disc space) to support NGINX operations is always a good idea. Insufficient resources can prevent NGINX from booting up or cause it to crash. We recommend using system monitoring tools or command-line utilities such as htop to examine resource consumption.

Reason # 2: PHP-FPM Isn’t Working

If you’re getting a 502 Bad Gateway error because NGINX and PHP-FPM aren’t “cooperating”, you can troubleshoot the problem by doing the following:

Examine the NGINX and PHP-FPM Configurations

Start by checking that NGINX and PHP-FPM are both correctly configured and functioning.

Open the NGINX configuration file (/etc/nginx/nginx.conf or /etc/nginx/conf.d/*) and verify that the location block for PHP scripts is correctly set up. It should have directives like fastcgi_pass, which points to the PHP-FPM socket or address and port, and fastcgi_param parameters.
Similarly, review the PHP-FPM configuration file (/etc/php-fpm.conf or /etc/php-fpm.d/www.conf) to ensure all settings are correctly set up.

Check the Status of PHP-FPM

Check to see if PHP-FPM is currently operational.

For this, launch the terminal or command prompt and type the following command:

$ sudo service php-fpm status

php fpm service status

This command displays PHP-FPM’s current status. If it isn’t up, you’ll receive a message that PHP-FPM isn’t running.

Restart NGINX and PHP-FPM

If NGINX and PHP-FPM are running but not communicating correctly, you can try restarting both services.

To restart them, use the following commands:

$ sudo service nginx restart
$ sudo service php-fpm restart

Examine the Socket or Address and Port Settings

Check that the fastcgi_pass directive in the NGINX configuration file is correctly pointing to the PHP-FPM socket or IP and port.

Here’s what a properly formatted directive looks like:
fastcgi_pass unix:/run/php/php7.4-fpm.sock;

If you use a TCP address and port, it should appear like this:

fastcgi_pass 127.0.0.1:9000;

Check that the socket or address and port correspond to the PHP-FPM settings. After modifying the configuration, remember to restart both NGINX and PHP-FPM.

Examine PHP-FPM Error Logs

PHP-FPM logs provide essential insight into any PHP script execution issues. Typically, the log file is located in /var/log/php-fpm.log.

Examine the log file for error messages that may illuminate the problem. While you’re at it, we suggest checking NGINX’s error log (/var/log/nginx/error.log) for any relevant error messages.

Examine the File Permissions

An overlooked reason behind PHP-FPM and NGINX-related issues is misconfigured file permissions.

You should confirm that the PHP files and directories have the necessary permissions and ownership so that NGINX can access them and PHP-FPM can execute them.
Typically, PHP files should be readable by the NGINX user, and folders should have appropriate execution rights. Use the chown and chmod commands to change ownership and permissions, if necessary.

Test Configurations With a Simple PHP Script

Write a simple PHP script (we highly recommend printing info.php) to test NGINX and PHP-FPM operations. For this, we suggest the following:

<?php phpinfo(); ?>

Put this line in a file named info.php and save the file in the web root directory (for example, /var/www/html). Now, visit it using your browser (for example, http://your-domain.com/info.php).

If you can see the PHP information page, the NGINX, and PHP-FPM are working successfully together. If not, it could point to a problem with PHP-FPM settings or communication between NGINX and PHP-FPM.

Reason # 3: The PHP-FPM Timeout Has Expired

The error “The PHP-FPM timeout has expired” usually means that a PHP script executed by PHP-FPM took longer to complete than the timeout value mentioned in the config file.

When PHP-FPM receives a request to execute a PHP script, a worker process is launched to fulfill the request. PHP-FPM terminates the process and returns the timeout error if the script execution exceeds the timeout setting defined in the PHP-FPM configuration.

You can resolve this problem by taking the following steps:

Increase the Value of the Timeout

In the PHP-FPM configuration file (typically /etc/php-fpm.conf or /etc/php-fpm.d/www.conf), change the request_terminate_timeout setting directive.

We suggest increasing the value of request_terminate_timeout to allow PHP scripts to run for extended periods.

For instance, in the following example, the timeout is set to 300 seconds (5 minutes):

request_terminate_timeout = 300s

We suggest adjusting the value to meet the needs of your application.

Restart PHP-FPM Service

If you change the PHP-FPM configuration file, you must restart the PHP-FPM service to implement the modifications.

The command may differ depending on your operating system and how PHP-FPM is installed. Here is an example of the restart commands:

$ sudo systemctl restart php-fpm

Improve Your PHP Code

If your PHP script takes too long to execute, you may need to optimize your code to improve its execution time frame. You should focus on finding and optimizing bottlenecks like database requests, intensive computations, or inefficient algorithms.

Check for Resource Constraints

Executing PHP scripts requires server resources. Time-out errors might also occur when a script gets stuck while waiting for the resources to continue execution.

As such, you should ensure that your server has sufficient resources to handle PHP script execution.

Reason # 4: NGINX Requests Denied by the Firewall

If you receive a “502 Bad Gateway” error in NGINX and think that the firewall is blocking requests, try the following ideas to troubleshoot the problem:

Examine the Firewall Rules

Start by checking the firewall rules to ensure it is not blocking inbound requests to NGINX.

Depending on your firewall solution ( iptables, UFW, or Firewalld), the rule syntax about port 80 for HTTP or port 443 for HTTPS might differ. You should check and allow inbound traffic to NGINX, and modify the rules accordingly.

Temporarily Disable the Firewall

As a first step in troubleshooting, temporarily disable the firewall and see if the 502 Bad Gateway error persists. This helps you narrow down the firewall as the source of the problem.

However, you should re-enable the firewall immediately to maintain security.

Examine the Firewall Logs

Check the firewall logs to see whether entries are linked to disallowed requests. In addition, firewall logs can give information about blocked traffic and the reasons for denials. The location of the firewall logs differs depending on the firewall solution. We suggest checking /var/log/iptables.log, /var/log/ufw.log, and /var/log/firewalld.log for the logs.

Allow NGINX Through the Firewall

We recommend allowing NGINX through the firewall to eliminate firewall-related causes of the NGINX 502 Bad Gateway error.

Start by configuring the necessary rules to allow NGINX through the firewall. Make changes to the firewall rules to allow inbound connections on the NGINX ports 80 and 443. The particular instructions or configuration procedures vary depending on the firewall solution.

Here are a couple of examples:

iptables

Use the following commands to whitelist ports 80 and 443 in iptables:

$ sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
$ sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

UFW (Simplified Firewall)
Use the following commands to whitelist ports 80 and 443 in UFW:

$ sudo ufw allow 80/tcp
$ sudo ufw allow 443/tcp

Firewalld
Use the following commands to whitelist ports 80 and 443 in Firewalld:

$ sudo firewall-cmd --add-service=http --permanent
$ sudo firewall-cmd --add-service=https --permanent
$ sudo firewall-cmd --reload

Test Connectivity

After modifying the firewall rules and validating the NGINX configuration, see if you can connect to NGINX.

Use programs such as Telnet or curl to verify connectivity locally and from remote systems. For example, to test NGINX’s response, use the following command:

# curl -I http://localhost/

If the connection is successful and the expected response is received, the firewall rules allow traffic to the NGINX reverse proxy server.

Reason # 5: A Domain Name is Not Permitted

If you get a “502 Bad Gateway” error message in NGINX with the message “A domain name is not permitted,” it usually means that NGINX received a request for a domain name not configured or allowed in the configuration file.

You can troubleshoot this problem by doing the following:

Check the server_name Directive

Start by checking the server_name directive to see if the domain name causing the problem is included in the directive block. The path should be: /etc/nginx/sites-available/domainname.conf

For example,
server_name example.com www.example.com;

nginx config file

If the domain name is missing or incorrect, add or change the server_name directive.

Examine DNS Resolution

Check that the domain name correctly resolves to the NGINX server’s IP address. You can do DNS lookups with tools like nslookup or dig to ensure the domain name resolves to the correct IP address. Here’s a sample lookup command:

# nslookup example.com

If the domain name does not resolve correctly, you may need to adjust your DNS configuration or contact your DNS provider.

Reason # 6: Bugs In Web Applications

Errors at the application level can (rarely) cause the 502 Bad Gateway error.

If your web server logs contain loading errors similar to the following, the application code may be incompatible with the server version and configuration.

[notice] child pid xxxxx exit signal Segmentation fault (11)

You must examine your application’s software needs and re-configure the services to meet the requirements.

Conclusion

The 502 Bad Gateway in NGINX error usually happens when NGINX runs as a reverse proxy and can’t connect to services on either side of the server setup. This error could occur because of a server crash, a network error, a problem with the NGINX setup, or domain-related issues.
Here at Redswitches, we offer The perfect platform for setting up NGINX as a Reverse Proxy server.

Optimizing a reverse proxy can make it run faster and handle calls more efficiently. Remember that the right configurations and optimizations may differ based on how you use the system and what you expect from the NGINX server. Redswitches is a one-stop solution for all of your website hosting needs.

FAQs

Q. What does the NGINX 502 Bad Gateway error indicate?

The 502 Bad Gateway error means an upstream server sent no or malformed response to the NGINX server in a reverse proxy server role. It usually happens when NGINX can’t connect to the backend server or when the backend server gives an invalid or unexpected response.

Q. Can too much traffic cause a 502 Bad Gateway?

Too much traffic can overwhelm the backend servers or the proxy infrastructure, causing the 502 Bad Gateway problem. In these situations, you may need to optimize your server resources, change timeouts, or use load balancers to handle the extra traffic.

Q. Can DNS problems result in a 502 Bad Gateway error?

Yes, a “502 Bad Gateway” error can be caused by trouble with DNS resolution. Ensure that the upstream server’s IP address can be found by resolving the domain name used in the NGINX setup.

Q. Can a PHP-FPM misconfiguration cause a 502 Bad Gateway error in NGINX? 

A 502 Bad Gateway problem in NGINX can happen if PHP-FPM is set up incorrectly. To avoid these errors, ensure that NGINX is set up correctly to talk to PHP-FPM using the correct socket, address, and port. Check the PHP-FPM configuration file (php-fpm.conf or www.conf) to ensure it conforms to the proper NGINX configuration settings.

A 502 Bad Gateway Nginx error is an HTTP status code that represents a server acting as a gateway or proxy server failing to receive a valid response from an upstream server. In the case of Nginx, a 502 bad gateway error occurs when the server cannot establish a connection with the upstream server or when the upstream server returns an invalid response.

This error is commonly seen when trying to access a website or web application that is hosted behind a reverse proxy or load balancer.

There are multiple variations of 502 Bad gateway Nginx Error you might find on different sites. For example:

  • HTTP Error 502- Bad Gateway
  • 502 Proxy Error
  • 502 Bad Gateway
  • 502 Service Temporarily Overloaded
  • HTTP 502
  • 502 Bad Gateway NGINX
  • Error 502

Nginx is a well-known open-source web server that is highly popular for its performance, scalability, and flexibility. However, similar to other web servers, Nginx can face errors that hinder its ability to deliver content to clients. One such error is the 502 Bad Gateway Nginx error.

Encountering errors can be quite frustrating and confusing, especially if you are not technically proficient. You may come across several similar prominent errors, such as the white screen of death, and the error establishing database connection. But 502 bad gateway nginx error is a very popular one.

There can be multiple possible reasons for this error to happen and therefore different ways to troubleshoot it. In this post, we will tell you what 502 bad gateway Nginx really means, its possible causes and what are the best troubleshooting method you must follow.

Let us get started!



Read: 🚩 15 Methods to Fix 502 Bad Gateway Error on Your Website


What Causes a 502 Bad Gateway Nginx Error?

There can be several reasons why a 502 Bad Gateway error may occur in Nginx, but here are some of the most common ones listed down below:

Server Overload

When a backend server receives too many requests, it can become overloaded and fail to respond within the timeout period. This causes a 502 error as the upstream server cannot fulfill the client’s request. Proper server sizing, resource allocation, load balancing, and scaling strategies can prevent server overload.

Connectivity Issues

  • Connectivity issues can cause a 502 Bad Gateway error in Nginx when there is a problem with the network connection between the reverse proxy server and the backend server.
  • This can happen due to network congestion, misconfigured network settings, or hardware failures.
  • When the reverse proxy server attempts to forward a request to the backend server but cannot establish a connection, it returns a 502 error to the client.
  • The error occurs because the reverse proxy server acts as an intermediary between the client and the backend server and is unable to connect to the backend server to fulfill the client’s request.
  • Troubleshooting network settings, checking firewall rules, and monitoring network traffic can help fix the issue.

DNS Issues

  • DNS issues can cause a 502 Bad Gateway error in Nginx when the DNS resolution for the backend server fails.
  • This can happen due to incorrect DNS configurations, DNS server failures, or DNS caching issues.
  • When a client sends a request to the reverse proxy server, the reverse proxy server needs to resolve the domain name of the backend server to an IP address.
  • If the DNS resolution fails, the reverse proxy server cannot forward the request to the backend server, resulting in a 502 error being returned to the client.

Read: 🚩 What is DNS?


Firewall Restrictions

  • Firewall restrictions can cause a 502 Bad Gateway error in Nginx when a firewall blocks the connection between the reverse proxy server and the backend server.
  • This can happen when the firewall is configured to restrict traffic to and from specific IP addresses or ports.
  • When the reverse proxy server attempts to connect to the backend server, but the firewall blocks the connection, it returns a 502 error to the client.
  • This occurs because the reverse proxy server acts as an intermediary between the client and the backend server and cannot establish a connection with the backend server to fulfill the client’s request.
  • To fix firewall-related issues causing a 502 error, you may need to adjust firewall rules to allow traffic to flow between the reverse proxy and backend servers.

Software Bugs

  • A 502 Bad Gateway error may occur due to a software bug or misconfiguration in the reverse proxy server or backend server.
  • This error can happen because of coding errors or misconfigurations of server modules or applications.
  • If the software or configuration of either server contains a bug, it may fail to handle requests or respond within the timeout period, resulting in a 502 error being returned to the client.
  • To fix software-related issues causing a 502 error, you may need to examine the logs of both the reverse proxy and backend servers to identify any errors or warning messages.

PHP-FMP is Taking too long to respond

  • PHP-FPM (FastCGI Process Manager) can cause a 502 Bad Gateway error in Nginx when it fails to respond within the timeout period or encounters a critical error.
  • This error can happen due to insufficient resources, misconfiguration, or a bug in the PHP code.
  • PHP-FPM is a popular way of running PHP applications in Nginx, where Nginx sends the request to PHP-FPM and it processes the PHP code and returns the result to Nginx, which then sends the response back to the client.
  • To fix PHP-FPM-related issues, you may need to adjust the PHP-FPM configuration to increase the number of processes or threads or adjust the timeout settings.
  • You may also need to examine the PHP code to identify and fix any bugs or performance issues.
  • Additionally, monitoring the server logs and system resources can help identify any patterns or trends that could indicate a larger issue with PHP-FPM.

Read: 🚩 How to Fix HTTP 504 Gateway Timeout Error?


How to Fix a 502 Bad Gateway Nginx?

Here are some best solutions that you can follow to fix a 502 Bad Gateway Nginx error:

  • Check the status of Nginx
  • Check Backend Server Status
  • Check the DNS configuration
  • Check the Firewall Configuration
  • Increase the Buffer Size
  • Restart Nginx Server
  • Check PHP-FPM status

Check the status of Nginx

The first thing you need to do is to check whether Nginx is running and responding to requests or not. To do that, run the following command given below:

systemctl status nginx

If the Nginx is running, you will get an output message something like this,

nginx.service - The nginx HTTP Server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2022-10-11 10:25:41 UTC; 1 days ago
Docs: https://httpd.nginx.org/docs/2.4/

If the Nginx is not running, you will get an output message something like this,

nginx.service - The nginx HTTP Server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: inactive (dead) since Fri 2022-10-11 10:25:41 UTC; 25s ago
Docs: https://httpd.nginx.org/docs/2.4/

Now, in case the Nginx is not running, you have to start it again by using the following command,

systemctl start nginx

Check Backend Server Status

  • Log in to the reverse proxy server that is hosting Nginx.
  • Open a terminal window and run the following command:

curl -I http://backend-server-ip-address/

• Replace “backend-server-ip-address” with the IP address of your backend server.

• Check the HTTP status code in the output of the command. If the backend server is running correctly, you should see a status code of 200 OK.

• If you receive a status code other than 200, it indicates that there may be an issue with the backend server. You can further investigate the issue by examining the logs of the backend server to identify any errors or warning messages.

Check the DNS configuration

If the DNS resolution fails, the reverse proxy server cannot forward the request to the backend server, resulting in a 502 Bad Gateway error being returned to the client. Therefore, it is important to verify that the DNS configuration for the backend server is correct.

To check the DNS configuration, you can perform the following steps:

  • Log in to the reverse proxy server that is hosting Nginx.
  • Open a terminal window and run the following command:

nslookup backend-server-domain-name

Replace “backend-server-domain-name” with the domain name of your backend server.

• Check the output of the command to verify that the correct IP address is returned for the backend server.

  • If the output of the command indicates that the DNS resolution failed, there may be an issue with the DNS configuration. You can further investigate the issue by checking the DNS settings for the domain name of the backend server, or by contacting your DNS provider for assistance.

Check the Firewall Configuration

It is advised to check the firewall logs for an unusual block. Sometimes Firewalls also prevent or block sites. To overcome this issue, you need to temporarily disable your firewalls and check whether the issue persists or is resolved.

Increase the Buffer Size

Increasing the buffer size allows Nginx to store more data from the server’s response, ensuring that the response is complete and error-free. To increase the buffer size, you need to edit the Nginx configuration file and add the following directives.

  • proxy_buffer_size: Sets the size of each buffer. The default value is usually 4K. You can increase it to a higher value depending on your server’s requirements. For example, to set the buffer size to 16K, add the following line to your configuration file:

proxy_buffer_size 16k;

  • proxy_buffers: Sets the number of buffers to allocate. The default value is usually 8. You can increase it to a higher value depending on your server’s requirements. For example, to set the number of buffers to 32 and the buffer size to 16K, add the following line to your configuration file:

proxy_buffers 32 16k;


Note: It’s important to note that increasing the buffer size and number of buffers will increase memory usage on the server. So, you should experiment with different buffer sizes and buffer numbers to find the optimal setting for your server and application.


  • After making changes to the Nginx configuration file, save the file and restart Nginx for the changes to take effect. You can do this by running the following command:

sudo service nginx restart

Restart Nginx Server

In some cases, just restarting the Nginx server may resolve the 502 bad gateway Nginx error. To do this,

You need to run a command in your terminal or shell. The exact command depends on the operating system and distribution you are using, but here are a few examples:

  • Ubuntu and Debian:

sudo service nginx restart

  • CentOS, Fedora, and RHEL:

sudo systemctl restart nginx

  • macOS:

sudo nginx -s reload

These commands will gracefully restart the Nginx server, meaning that it will wait for any active connections to finish before shutting down and starting again.

Check PHP-FPM status

Sometimes, the 502 Bad Gateway Nginx error can also be triggered by PHP-FPM not running. Therefore, it is necessary to check the status of PHP-FPM to ensure it is running properly.

To check the running status, you can use the following command,

sudo service php-fpm status

If PHP-FPM is running, you should see a message stating that it is active.

However, in case PHP-FPM is not running, you can try restarting it using the following command:

sudo service php-fpm restart

This command will restart the PHP-FPM service, which can help resolve any issue that might be triggering a 502 bad gateway Nginx error.


Summary

A 502 Bad Gateway Nginx error is a common error that Nginx users may encounter. It is typically caused by connectivity issues, server overload, DNS issues, firewall restrictions, or software bugs.

However, following the steps outlined in this article, you can troubleshoot and resolve a 502 bad gateway nginx error.

If none of the above methods have worked for you, unfortunately, consider seeking assistance from Nginx forums or a highly experienced and qualified Nginx consultant.

If you have any tips or suggestions regarding the 502 Bad Gateway Nginx error that we may have missed in this post or if you would like to share your experience with the same, please let us know in the comment section below. We welcome your input.


Read: 🚩 How to fix HTTP 500 Internal Server Error in WordPress?


Frequently Asked Questions

How do I fix 502 Bad gateway nginx?

You can fix 502 Bad Gateway nginx error by following the below methods:
1. Check the status of Nginx
2. Check Backend Server Status
3. Check the DNS configuration
4. Check the Firewall Configuration
5. Increase the Buffer Size
6. Restart Nginx Server
7. Check PHP-FPM stat

How do I check my nginx status?

To check the nginx status, Run the following command given below:
systemctl status nginx
The Output will show whether the nginx is running or not.

What is a 502 Bad gateway error?

A 502 Bad Gateway Nginx error is an HTTP status code that represents a server acting as a gateway or proxy server failing to receive a valid response from an upstream server.

Недорогой хостинг для сайтов

hosting.energy недорогой хостинг сайтов

В этом руководстве мы покажем вам, как исправить 502 ошибки неверного шлюза на веб-сервере Nginx. Если вы запускаете веб-сервер Nginx, вы, возможно, уже столкнулись с досадной ошибкой 502 плохого шлюза. Это довольно распространенная ошибка, скорее всего, вызванная настройками буфера PHP или FastCGI и тайм-аутов. Из этого туториала Вы узнаете, как исправить плохой шлюз Nginx 502 на веб-сервере Nginx. В этом сообщении показано, как решить эту проблему, а также параметры конфигурации, чтобы предотвратить ее повторное появление при перезагрузке.

В этой статье предполагается, что у вас есть хотя бы базовые знания Linux, вы знаете, как использовать оболочку, и, что наиболее важно, вы размещаете свой сайт на собственном VPS. Установка довольно проста и предполагает, что вы работаете с учетной записью root, в противном случае вам может потребоваться добавить ‘ sudo‘ к командам для получения привилегий root. Я покажу вам пошаговое решение ошибки 502 неверного шлюза на веб-сервере Nginx.

Исправить ошибку 502 Bad Gateway на Nginx

Шаг 1. Сначала проверьте журнал данных веб-сервера Nginx.

Вы можете более подробно увидеть, что конкретно влечет за собой ошибка, перейдя в файл журнала ошибок вашего веб-сервера. Вся информация об ошибках и диагностическая информация хранится в этом файле, что делает его ценным ресурсом для проверки, когда вам нужны дополнительные сведения о конкретной ошибке. Вы можете найти этот файл в Nginx, перейдя в ./var/log/nginx/error.log

Шаг 2. Решите 502 проблемы со шлюзом.

  • Метод 1. Изменения в Nginx Config.

Выполните следующую команду, чтобы отредактировать Nginx conf:

sudo nano /etc/nginx/nginx.conf
http {
    ...
    fastcgi_buffers 8 16k;
    fastcgi_buffer_size 32k;
    ...
}

После этого перезапустите службу Nginx, чтобы вступили в силу:

sudo nginx -t
sudo systemctl restart nginx
  • Метод 2. Измените PHP-FPM для прослушивания сокета Unix или сокета TCP.
nano /etc/php-fpm.d/www.conf
listen = /var/run/php5-fpm.sock

To:

listen = 127.0.0.1:9000

После этого перезапустите PHP-FPM, чтобы изменить эффект:

sudo systemctl restart php-fpm

Если вы настраиваете php-fpm для прослушивания сокета Unix, вы также должны проверить, что у файла сокета есть правильный владелец и разрешения.

chmod 0660 /var/run/php5-fpm.sock
chown www-data:www-data /var/run/php5-fpm.sock
  • Метод 3. Отключить APC.

Кэширование APC может вызвать проблемы 502 Bad Gateway в определенных средах, вызывая ошибки сегментации. Я настоятельно рекомендую использовать Memcache (d), но XCache также является хорошей альтернативой.

Поздравляю! Вы успешно решили 502 проблемы со шлюзом. Благодарим за использование этого руководства для исправления 502 проблем со шлюзом в системе Linux. Для получения дополнительной помощи или полезной информации мы рекомендуем вам посетить официальный сайт Nginx .

Рекомендуемый контент


Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Ошибка 5006 0x80070005 при работе программы установки
  • Ошибка 502 ru center
  • Ошибка 501 при отправке почты
  • Ошибка 501 на газовом котле алексия
  • Ошибка 5014 bmw

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии