Код ошибки 499

NginX выдает ошибку HTTP 499 через 60 секунд, несмотря на конфигурацию. (PHP и AWS)

В конце прошлой недели я заметил проблему на одном из моих средних экземпляров AWS, где Nginx всегда возвращает ответ HTTP 499, если запрос занимает более 60 секунд. Запрошенная страница представляет собой скрипт PHP

Я провел несколько дней, пытаясь найти ответы, и попробовал все, что я могу найти в Интернете, включая несколько записей здесь, в Stack Overflow, ничего не работает.

Я пробовал изменять настройки PHP, настройки PHP-FPM и настройки Nginx. Вы можете увидеть вопрос, который я поднял на форумах NginX в пятницу ( https://forum. nginx. org/read. php?9,237692 ), хотя он не получил ответа, поэтому я надеюсь, что я смогу найти ответьте здесь, прежде чем я вынужден вернуться к Apache, который, как я знаю, работает.

Это не та же проблема, что и ошибки HTTP 500 в других записях.

Я смог реплицировать проблему с помощью нового экземпляра micro AWS NginX с использованием PHP 5.4.11.

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

Вам нужно будет запустить новый экземпляр AWS Micro (поэтому он бесплатный) с помощью AMI ami-c1aaabb5

Эта запись PasteBin имеет полную настройку для запуска, чтобы отразить мою тестовую среду. Вам просто нужно изменить example. com в конфигурации NginX в конце

Как только вы настроитесь, вам просто нужно создать образец файла PHP, который я тестирую, с которым

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

Обновите PHP FPM Config, чтобы включить внешние файлы конфигурации

Создайте новую конфигурацию PHP-FPM для переопределения таймаута запроса

Измените некоторые глобальные настройки, чтобы обеспечить интервал аварийного перезапуска 2 минуты

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

Как вы можете видеть, это увеличивает тайм-аут сокета до 3 минут и помогает регистрировать ошибки.

Наконец, я отредактирую некоторые параметры NginX, чтобы увеличить тайм-аут той стороны

Сначала я редактирую файл /etc/nginx/nginx. conf и добавляю его в директиву http fastcgi_read_timeout 300;

Затем я редактирую файл / etc / nginx / sites-enabled / example, который мы создали ранее (см. Запись pastebin), и добавьте следующие параметры в директиву сервера

Наконец, я добавляю следующее в раздел

Прежде чем повторять сценарий, запустите nginx и php-fpm, чтобы убедиться, что новые настройки были подняты. Затем я пытаюсь получить доступ к странице и все еще получаю запись HTTP / 1.1 499 в файле NginX example. error. log.

Итак, где я иду не так? Это просто работает на apache, когда я устанавливаю максимальное время выполнения PHP до 2 минут.

Обновление 1

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

Если я запустил скрипт с веб-страницы, я увижу, что содержимое файла будет установлено в первую строку. Через 60 секунд в журнале NginX появляется ошибка. Через 10 секунд содержимое файла изменяется на вторую строку, доказывая, что PHP завершает процесс.

Обновление 2

Установка fastcgi_ignore_client_abort; изменяет ответ от HTTP 499 на HTTP 200, хотя ничего не возвращается конечному клиенту.

Обновление 3

Установив Apache и PHP (5.3.10) на поле прямо (используя apt), а затем увеличивая время выполнения, проблема также возникает и на Apache. Симптомы такие же, как и у NginX, ответ HTTP200, но фактическое время соединения с клиентом перед раздачей.

Я также начал замечать в журналах NginX, что если я тестирую с помощью Firefox, он делает двойной запрос (например, этот PHP-скрипт выполняется дважды, когда он длится более 60 секунд ). Хотя, похоже, это клиент, запрашивающий при неудачном сценарии

Причиной проблемы является эластичная балансировка нагрузки на AWS. Они, по умолчанию, тайм-аут после 60 секунд бездействия, что и вызывало проблему.

Так что это не NginX, PHP-FPM или PHP, а балансировка нагрузки.

Чтобы исправить это, просто зайдите на вкладку «Описание» ELB, прокрутите страницу вниз и нажмите ссылку «(Изменить)» рядом со значением, обозначающим «Idle Timeout: 60 секунд»,

Я думал, что оставлю свои два цента. Сначала проблема не связана с php (все еще может быть связано с php, php всегда меня удивляет: P). Это уж точно. в основном это вызвано сервером, проксированным для себя, в частности, имена имен хостов / псевдонимов, в вашем случае это может быть балансировка нагрузки, запрашивающая nginx, и nginx обращается к балансировщику нагрузки и продолжает идти таким образом.

Я столкнулся с аналогичной проблемой с nginx в качестве балансировки нагрузки и apache в качестве веб-сервера / прокси-сервера

Вам нужно найти, в каком месте проблемы жить. Я не знаю точного ответа, но просто попробуем его найти.

У нас есть 3 элемента: nginx, php-fpm, php. Как вы сказали, одинаковые настройки php под apache в порядке. Разве это не такая же настройка? Вы пытались apache вместо nginx на той же ОС / хосте / и т. Д.?

Если мы увидим, что php не подозревает, у нас есть два подозреваемых: nginx & php-fpm.

Чтобы исключить nginx: попробуйте настроить ту же «систему» ​​на рубине. См. https://github. com/garex/puppet-module-nginx, чтобы получить представление об установке простейшей рубиновой установки. Или используйте google (возможно, это будет еще лучше).

Мой главный подозреваемый здесь – php-fpm.

Попробуйте сыграть с этими настройками:

На самом деле я столкнулся с той же проблемой на одном сервере, и я понял, что после изменений конфигурации nginx я не перезапустил сервер nginx, поэтому с каждым ударом nginx-url я получал ответ 499 http. После перезапуска nginx он начал нормально работать с ответами HTTP 200.

Nginx 499 error codes

I am getting a lot of 499 nginx error codes. I see that this is a client side issue. It is not a problem with Nginx or my uWSGI stack. I note the correlation in uWSGI logs when a get a 499.

I am looking for a more indepth explanation and hoping it is nothing wrong with my nginx config for uwsgi. I am taking it on face value. its not a me problem..its a client issue.

14 Answers 14

HTTP 499 in Nginx means that the client closed the connection before the server answered the request. In my experience is usually caused by client side timeout. As I know it’s an Nginx specific error code.

In my case, I was impatient and ended up misinterpreting the log.

In fact, the real problem was the communication between nginx and uwsgi, and not between the browser and nginx. If I had loaded the site in my browser and had waited long enough I would have gotten a «504 — Bad Gateway». But it took so long, that I kept trying stuff, and then refresh in the browser. So I never waited long enough to see the 504 error. When refreshing in the browser, that is when the previous request is closed, and Nginx writes that in the log as 499.

Elaboration

Here I will assume that the reader knows as little as I did when I started playing around.

My setup was a reverse proxy, the nginx server, and an application server, the uWSGI server behind it. All requests from the client would go to the nginx server, then forwarded to the uWSGI server, and then response was sent the same way back. I think this is how everyone uses nginx/uwsgi and are supposed to use it.

My nginx worked as it should, but something was wrong with the uwsgi server. There are two ways (maybe more) in which the uwsgi server can fail to respond to the nginx server.

1) uWSGI says, «I’m processing, just wait and you will soon get a response». nginx has a certain period of time, that it is willing to wait, fx 20 seconds. After that, it will respond to the client, with a 504 error.

2) uWSGI is dead, or uWSGi dies while nginx is waiting for it. nginx sees that right away and in that case, it returns a 499 error.

I was testing my setup by making requests in the client (browser). In the browser nothing happened, it just kept hanging. After maybe 10 seconds (less than the timeout) I concluded that something was not right (which was true), and closed the uWSGI server from the command line. Then I would go to the uWSGI settings, try something new, and then restart the uWSGI server. The moment I closed the uWSGI server, the nginx server would return a 499 error.

So I kept debugging with the 499 erroe, which means googling for the 499 error. But if I had waited long enough, I would have gotten the 504 error. If I had gotten the 504 error, I would have been able to understand the problem better, and then be able to debug.

So the conclusion is, that the problem was with uWGSI, which kept hanging («Wait a little longer, just a little longer, then I will have an answer for you. «).

How I fixed that problem, I don’t remember. I guess it could be caused by a lot of things.

Client closed the connection doesn’t mean it’s a browser issue!? Not at all!

You can find 499 errors in a log file if you have a LB (load balancer) in front of your webserver (nginx) either AWS or haproxy (custom). That said the LB will act as a client to nginx.

If you run haproxy default values for:

That would mean that LB will time out after 60000ms if there is no respond from nginx. Time outs might happen for busy websites or scripts that need more time for execution. You’ll need to find timeout that will work for you. For example extend it to:

And you will be probably set.

Depending on your setup you might see a 504 gateway timeout error in your browser which indicates that something is wrong with php-fpm but that will not be the case with 499 errors in your log files.

In my case I got 499 when the client’s API closed the connection before it gets any response. Literally sent a POST and immediately close the connection. This is resolved by option:

As you point 499 a connection abortion logged by the nginx. But usually this is produced when your backend server is being too slow, and another proxy timeouts first or the user software aborts the connection. So check if uWSGI is answering fast or not of if there is any load on uWSGI / Database server.

In many cases there are some other proxies between the user and nginx. Some can be in your infrastructure like maybe a CDN, Load Balacer, a Varnish cache etc. Others can be in user side like a caching proxy etc.

I’ll recommend you to set:

This provides a correct chain of timeouts. and you’ll find really whose giving the timeout and return the right response code to the user.

Turns out 499’s really does mean «client interrupted connection.»

I had a client read timeout of 60s (and nginx also has a default proxy_read_timeout of 60s). So what was happening in my case is that nginx would error. log an upstream timed out (110: Connection timed out) while reading upstream and then nginx retries «the next proxy server in the backend server group you configured.» That’s if you have more than one.

Then it tries the next and next till (by default) it has exhausted all of them. As each one times out, it removes them from the list of «live» backend servers, as well. After all are exhausted, it returns a 504 gateway timeout.

So in my case nginx marked the server as «unavailable», re-tried it on the next server, then my client’s 60s timeout (immediately) occurred, so I’d see a upstream timed out (110: Connection timed out) while reading upstream log, immediately followed by a 499 log. But it was just timing coincidence.

If all servers in the group are marked as currently unavailable, then it returns a 502 Bad Gateway. for 10s as well. See here max_fails and fail_timeout. Inn the logs it will say no live upstreams while connecting to upstream.

If you only have one proxy backend in your server group, it just try’s the one server, and returns a 504 Gateway Time-out and doesn’t remove the single server from the list of «live» servers, if proxy_read_timeout is surpassed. See here «If there is only a single server in a group, max_fails, fail_timeout and slow_start parameters are ignored, and such a server will never be considered unavailable.»

The really tricky part is that if you specify proxy_pass to «localhost» and your box happens to also have ipv6 and ipv4 «versions of location» on it at the same time (most boxes do by default), it will count as if you had a «list» of multiple servers in your server group, which means you can get into the situation above of having it return «502 for 10s» even though you list only one server. See here «If a domain name resolves to several addresses, all of them will be used in a round-robin fashion.» One workaround is to declare it as proxy_pass https://127.0.0.1:5001; (its ipv4 address) to avoid it being both ipv6 and ipv4. Then it counts as «only a single server» behavior.

There’s a few different settings you can tweak to make this «less» of a problem. Like increasing timeouts or making it so it doesn’t mark servers as «disabled» when they timeout. or fixing the list so it’s only size 1, see above ?

Ошибки клиента (400 — 499)

Эта группа кодов статуса HTTP означает, что запрос клиента не может быть выполнен — либо запрос ошибочный, либо на подобные запросы настройками сервера наложены ограничения. Ошибки этой группы не связаны со сбоем или перегрузкой сервера (ошибки сервера отражает группа статусов 500 – 599).

400 Bad Request

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

401 Unauthorized

402 Payment Required

403 Forb >

Доступ запрещен. Сервер распознал запрос, но в доступе отказано. Отказ не связан с авторизацией, а обусловлен настройками сервера, клиент не должен повторять запрос к запрещенной области. Сервер должен отправить сообщение с объяснением отказа. Если доступ невозможен временно и сообщение о запрете нежелательно, то вместо этого статуса нужно использовать 404.

404 Not Found

405 Method Not Allowed

406 Not Acceptable

В настоящий момент этот ответ реализуется упрощенно — если медиатип ресурса не совпадает ни с одним из списка типов, перечисленных в поле Accept запроса, то в ответ посылается статус 406 и сообщение о несоответствии.

407 Proxy Authentication Required

408 Request Timeout

Клиент не послал запрос в течение того интервала времени, когда сервер его ожидал. Запрос может быть отправлен повторно.

409 Conflict

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

410 Gone

Запрошенный документ больше не существует. Это состояние следует понимать как постоянное — точно известно, что документ удален с сервера, а не перемещен на какой-либо другой адрес. Клиенту рекомендуется по согласованию с пользователем удалить ссылки на запрошенный URI и больше по нему не обращаться.

411 Length Required

Сервер отказал в доступе по запросу с не определенным полем Content-Length в заголовке. Клиент может повторить запрос, если добавит в заголовок поле Content-Length с указанием длины «тела» запроса. Обычно применимо для POST-запросов.

412 Precondition Failed

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

413 Request Entity Too Large

Сервер отказывает в обработке запроса, поскольку запрошенный объект слишком велик — больше, чем сервер в состоянии обработать. Сервер может закрыть соединение, чтобы помешать клиенту продолжать запрос. Если это состояние является временным, сервер должен включить в заголовок ответа поле Retry-After с указанием, через какое время клиент может попытаться повторить запрос.

414 Request-URI Too Long

415 Unsupported Media Type

Формат объекта запроса не поддерживается запрашиваемым ресурсом для данного метода запроса.

416 Requested Range Not Satisfiable

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

С этим статусом сервер должен отправить в заголовке поле Content-Range с указанием актуальной длины запрошенного объекта.

417 Expectation Failed

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

На текущий момент это полный список возможных откликов на ошибочные запросы, точно определенных в RFC 2616.

HTTP 499 Error Code

There are numerous HTTP error codes out there, but let’s talk about the 499 error code. We can also refer to the 499 error code as HTTP code 499, or HTTP error 499. But whatever you call it, the 499 error code is something worth understanding. HTTP code 499 can happen anytime without you knowing, so let’s get started with getting to know HTTP error 499.

Eliminate errors and get Seamless Content Delivered

What is 499 Error Code?

Error 499

The error 499 code was created by the minds behind NGINX, a high-performance web server. Being a prominent web server, NGINX created HTTP error 499 code to handle its specific error. For starters, HTTP error 499 part of a massive list of HTTP error codes, all pertaining to various requests done during online activity. Various entities connect to each other and request for certain data. HTTP error 499 basically means that the client, the request’s receiver, was not able to complete it. Compared to other error codes pertaining to forbidden requests or missing data, the 499 error code centers on errors pertaining to the client.

HTTP error 499 isn’t that specific. There are various reasons why the client wasn’t able to process the request, and ended up with a 499 error code. An example of an occurrence which led to HTTP code 499 is that the client got loaded up on data traffic, it had to shut down. For example, it’s highly possible that a content delivery network had to close the request because it is already loaded with other data-related concerns, like a high cache volume. HTTP error 499 happened because in the process of the request, the content delivery network had to attend to more internal problems, so as a client, it had to cancel the request.

Where does the 499 error code appear?

HTTP code 499 usually is seen in NGINX’s logs. Being a web server, NGINX 499 is able to identify that the problem is not in the server itself, or the entity which sent the request. HTTP error 499 simply means that the client shut off in the middle of processing the request through the server. The 499 error code puts better light that something happened with the client, that is why the request cannot be done. So don’t fret: HTTP response code 499 is not your fault at all.

What are other reasons why HTTP error 499 happened?

As established, HTTP code 499 is not the fault of the server or the requesting party, and maybe not even the fault of the client. HTTP code 499 can occur differently for various clients. It was established earlier that the client can be a website or an app, and these two experience errors differently. A website leading to HTTP code 499 may have been loaded with too much traffic, or the request was from faulty algorithms that created problems within the website. The HTTP error may also happen because of faulty programming. For example, some apps are cloud based, and the server will do the effort in reaching out to their cloud apps. However, there was a problem with the coding of the online app. HTTP error 499 appears because the app cannot process the request, due to faulty programming. This is another illustration of how the client, the online app, led to HTTP code 499.

More on Client Errors

HTTP code 499 is only one of many client-related error codes. In general, error codes are classified into five categories, labeled by the first number in their 3 digits. For codes 400-499, these are all client-based errors, meaning the server request cannot be completed at all because of problems on the side of the client. The most common of this group where HTTP error 499 belongs is the 404 error: File on Found. Unlike HTTP code 499, the 404 code is very straightforward and definite, whereas the 499 error code simply generalizes that the client cannot complete the request of the server.

If you are interested to know more about HTTP error 499 and other codes, it would be a good idea to study how server logs work and how you can make sense of the information stored in such logs. This will also give you more perspective in identifying specific clients, like apps and websites, that end up with HTTP code 499 the most, so that you can be more mindful of what apps and websites to visit. But in general, being familiar with the 499 error code and other codes will help you navigate the Web better.

Get rid of HTTP errors and Power up your Content Delivery

Источники:

https://top-office11.ru/oshibki-i-problemy/kod-oshibki-499.html

https://www. belugacdn. com/499-error-code/

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

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: