414 request uri too large nginx как исправить

Ошибка 414 Request URI Too Large возникает в тех случаях, когда веб-сервер не способен обслужить запрос от клиента (т.е. веб-браузера или робота), потому что запрашиваемый URI (Request URI) длиннее, чем сервер может интерпретировать. Говоря простым языком, запрашиваемый веб-адрес слишком длинный, то есть содержит слишком много байтов.

Так что если адрес верный и не содержит лишнего мусора, то самым простым способом решения проблемы будет реконфигурация веб-сервера. В качестве примера воспользуемся Nginx. Необходимо в файле конфигурации nginx.conf, который обычно расположен в /etc/nginx/nginx.conf добавить или изменить в секцииserver или http и https строчку:
large_client_header_buffers 4 16k

Здесь 16k байт и будет желаемым размером URL-адреса, а 4 — количеством желаемых буферов. В данному случае размер буферов более важен, чем их количество, так что в большинстве случаев параметр 4 будет оптимальным.

Для настройки сервера на базе Apache меняем параметр LimitRequestFieldSize в файле конфигурации на желаемое значение (в байтах).

Длина URI не предусмотрена спецификацией

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

Источник


WordPress errors don’t happen too often, given the stable codebase. What’s more, when something does pop up to dampen your day, it’s explicit. The 414 Request-URI Too Large error, for one, tells you exactly what the problem is. From there, you can attempt to fix it.

Much like many other WordPress errors, there are some specific steps you can take to resolve it. In short, you’ll need to adjust some configuration settings to allow for longer URLs. Once you’re finished, the error will be too.

In this article, we will walk you through how to fix the 414 Request-URI Too Large error. It will include the tools and skills you’ll need to solve the problem and list some “pre-steps” before getting under the hood.

Check out our video guide to fixing the 414 Request-URI Too Large error:

What the 414 Request-URI Too Large Error Is (And Why It Happens)

The 414 Request-URL Too Large error is a configuration issue. It’s one of the 400 error codes. They’re troublesome because it often means there’s a critical issue somewhere between your browser and a server.

In this case, a 414 error means that the URL is too long for the server to process, so it throws an exception. This could be an issue when using Urchin Tracking Module (UTM) codes to track conversions. These links can get long depending on the parameters you set, and if they reach the maximum limit of your site’s configuration, you’ll see the error.

As with many WordPress errors, there are many more things going on under the hood to cause a 414. In fact, you can group the causes into three distinct areas:

  • Converting a POST request to a GET request with query information that is too long. This is a developer-specific issue that happens at the coding level.
  • A redirect loop. We’ve talked about the best practices for redirects in a previous post. If you get into a redirect loop, the resulting URLs get too long, and the error will appear.
  • The server could be under attack, and a 414 error at this point will be the least of your worries.

Before we move on, it’s worth noting that for all intents and purposes, a URI and a URL are the same things. While there are some distinct differences between the two, we’re going to use “URL” here to keep things straightforward.

Ever seen this error pop up? 😅 Tackle it with no fear thanks to this guide 💪Click to Tweet

What You’ll Need to Fix the 414 Request-URI Too Large Error

If you’ve encountered the 413 Request Entity Too Large error in the past, you’ll find a 414 error to be similar. Of course, the names show their similarities, as they’re next to each other in the official standards and have almost identical descriptions.

Given this, the list of tools and skills you’d use for fixing a 413 will be the same for a 414 too:

  • Administrative access to your server
  • One of the many Secure File Transfer Protocol (SFTP) clients available
  • The right skills to use SFTP and navigate your server
  • A clean and current backup on hand in case you need to restore
  • A text editor, though this might not be necessary for you

If you’re a Kinsta customer, you’ll find your SFTP credentials within the MyKinsta dashboard, along with some other handy functionality to get into your server:

The SFTP panel in the MyKinsta dashboard.

The SFTP panel in the MyKinsta dashboard.

It’s also worth noting that we will connect through SFTP here because it’s more secure (hence the name).

What to Do Before You Begin Resolving the 414 Request-URI Too Large Error

Before you crack open the hood on your server and set it to work, you may want to carry out some “pre-steps” first. It could be that there’s a simple workaround that doesn’t involve you tinkering with your configuration files.

What’s more, these checks should be carried out at some point regardless, so getting them taken care of now will help in the long run.

First, a WordPress plugin might generate long URLs as part of its functionality. Full-featured, all-in-one security plugins can be a prime candidate here, especially if they offer lots of functionality.

It’s hard to know at a glance whether a plugin could be at fault, but it’s worth investigating its specific settings for a dedicated option to restrict the length of URLs. If so, toggling this could solve the 414 error within seconds.

Under normal circumstances, though, there are a few other tasks you can carry out to help you diagnose the error:

  • Check your server logs for mentions of the error or any other identifying entries.
  • Your browser developer tools may give you some indication of the error’s cause — especially your Console.
  • Reach out to the site owner or developer (if it’s not you) and let them know the error exists. It could be that they will have a fix or can advise you further on what to do.

Of course, you may want to contact both the site and plugin developers anyway if you’ve found that a plugin is at fault. Even so, if you’ve exhausted all of your outreach and top-level checks, it’s time to venture on.

How to Fix the 414 Request-URI Too Large Error (In 3 Steps)

Once you have your tools together, you’ll need a plan. The fix for the 414 Request-URI Too Large error is to alter a server configuration file. As such, there are three steps you can take.

Let’s start by getting into your server and figuring out which type of server you have.

1. Log In to Your Server (And Determine Your Server Type)

You have to get into the server before you work on it, and this is where your SFTP skills come into play.

We’ve outlined how to get into your site through SFTP in the past, and once you’re in, you’ll need to figure out what type of server you have. There are two main types: Apache and Nginx.

It could be that you already know which server type you run. If so, you can skip to the next step.

If you’re struggling, here’s a quick tip: look for a .htaccess file. It’s found in the root of your server, and if you can see it, this means you’re running an Apache server. Nginx servers use a different configuration file.

That said, it could be that you’re running an Apache server that doesn’t yet have a .htaccess file. As such, there are two other methods you could use:

  • Carry out a domain lookup using the Whois Domain Tools site: This might tell you the type of server you’re using, although it’s not a foolproof method.
  • Check with your hosting provider about the server type you use. Of course, your host is going to know what server you run. Kinsta customers will always use Nginx servers, although other providers may use Apache or a mix. It’s best to open a ticket with your host to check before you poke around in your site’s backend.

When you’ve determined which type of server you use, you can head onto the next step and find your configuration file.

2. Find the Server Configuration File and Open It in Your Text Editor

As we noted, Apache servers use a .htaccess file for basic server configuration, and it will be located in your root directory. This isn’t the file you need to fix the 414 Request-URI Too Large error, though.

In this case, you’ll need to go deeper into your advanced configuration settings. These are found not at your site’s root folder but the server’s root.

When you log into your site through SFTP, you’ll often come to a directory that contains all of your sites (along with some other files). In many cases, you can go up a couple of levels to a server root directory:

Navigating to the server root in Cyberduck.

Navigating to the server root in Cyberduck.

This will give you a few more directories to traverse. Among them will be the etc folder:

The etc folder within a server root directory.

The etc folder within a server root directory.

The full path of the configuration file will be /etc/apache2/apache2.conf.

The Apache configuration file.

The Apache configuration file.

For Nginx servers, the process is similar. It’s one we’ve covered in part within our article on adjusting the maximum upload size in WordPress. The path to the configuration file will be /etc/nginx/nginx.conf.

Once you’ve located your file, open it in your favorite text editor. At this point, you’re ready to adjust it.

3. Adjust the Configuration File To Allow for Longer URLs

Much like how Apache and Nginx servers have different configuration files, they also have different settings to adjust. Regardless of your server type, though, you’ll need to open it in an editor if you haven’t already done so. Our preferred approach is to download the file to your computer, work on it, and upload it back to the server.

For Apache configuration files, look for the LimitRequestLine setting, or add it to the bottom of your file if it’s not there:

Changing the Apache server configuration settings.

Changing the Apache server configuration settings.

For the value, use at least 128000. If you need to go higher than this, keep to multiples of two (i.e. the next value should be 256000).

For Nginx servers, you’re looking for the large_client_header_buffers setting. Here, you’ll see two values relating to number and size. For example, large_client_header_buffers 4 8K. The only figure you need to alter here is the size — you can go from 8K to around 128K, although you may need to increase this further (again in multiples of two).

Once you’re done, save your changes and upload your configuration file back to your server. At this point, check your site again, and the 414 Request-URI Too Large error should have gone.

The 414 Request-URI Too Large error may be annoying, but luckily, it tells you exactly what the problem is. 🤷‍♀️ Learn how to fix it here 👇Click to Tweet

Summary

WordPress errors often have a similar approach for resolving them. You’ll often need to diagnose the error first, though. In the case of the 414 Request-URI Too Large error, the problem is clear: the URLs being passed to the server are too big.

To fix it, you’ll need to change your Apache or Nginx server settings. This doesn’t take too long, and once you’re done, you should be back up and running. While we can’t speak for other hosts, Kinsta’s support team is on hand 24/7 to help you get over the 414 Request-URI Too Large error if you’re stuck. In fact, we’re here whenever you need our help and guidance, so you can get back to running your site.

I am using Nginx in front of 10 mongrels.

When I make a request with size larger then 2900 I get back an:

error code 414: uri too large

Does anyone know the setting in the nginx configuration file which determines the allowed uri length ?

Roald Nefs's user avatar

asked Jul 1, 2009 at 4:59

Prakash Raman's user avatar

Prakash RamanPrakash Raman

13.2k27 gold badges81 silver badges132 bronze badges

From: http://nginx.org/r/large_client_header_buffers

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

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

so you need to change the size parameter at the end of that line to something bigger for your needs.

Community's user avatar

answered Jul 1, 2009 at 5:46

Stobor's user avatar

9

For anyone having issues with this on https://forge.laravel.com, I managed to get this to work using a compilation of SO answers;

You will need the sudo password.

sudo nano /etc/nginx/conf.d/uploads.conf

Replace contents with the following;

fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;

client_max_body_size 24M;
client_body_buffer_size 128k;

client_header_buffer_size 5120k;
large_client_header_buffers 16 5120k;

answered Jan 18, 2019 at 16:12

Luke Snowden's user avatar

Luke SnowdenLuke Snowden

3,9512 gold badges37 silver badges70 bronze badges

1

I had very similar issue but with a different error

upstream sent too big header while reading response header from upstream

In order to fix it I’ve changed

server {
....
proxy_buffers   4 32k;
proxy_buffer_size   32k;
...
}

For more information you can visit nginx-doc

answered Feb 23, 2022 at 13:30

ciostek223's user avatar

ciostek223ciostek223

5145 silver badges6 bronze badges

Ошибка 414 Request URI Too Large возникает в тех случаях, когда веб-сервер не способен обслужить запрос от клиента (т.е. веб-браузера или робота), потому что запрашиваемый URI (Request URI) длиннее, чем сервер может интерпретировать. Говоря простым языком, запрашиваемый веб-адрес слишком длинный, то есть содержит слишком много байтов.

Обычно в настройках веб-сервера заданы довольно широкие лимиты на длину URL-адресов, от 2k и вплоть до 8k символов. В Nginx задается число и размер буферов.

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

Необходимо в файле конфигурации nginx.conf, который обычно расположен в /etc/nginx/nginx.conf добавить или изменить в секции server или http и https строчку: large_client_header_buffers 4 16k — изменение количества и размера буферов.

Здесь 16k байт и будет желаемым размером URL-адреса, а 4 — количеством желаемых буферов. В данному случае размер буферов более важен, чем их количество, так что в большинстве случаев параметр 4 будет оптимальным.

Длина URI не предусмотрена спецификацией

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

Решение проблемы методом POST

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

GET против POST

Пара переменной и ее значения в GET передается через URL-запрос:

GET /blog/?name1=value1&name2=value2 HTTP/1.1
Host: domain.com

пример GET-запроса.

Тогда как в POST она передается в теле самого заголовка:

POST /blog/ HTTP/1.1
Host: domain.com
name1=value1&name2=value2

пример POST-запроса.

Метод POST имеет ряд преимуществ перед GET: он более защищен, ведь большая часть запроса скрыта от пользователя; подходит для операций с большими данными.

На сервере установлена связка Django-UWSGI-Nginx. Иногда приходится обрабатывать GET запросы в которых количество символов ~ 40000 штук.

При таких запросах Nginx отдаёт 414 Request-URI Too Large. В настройки сервера внёс строчку large_client_header_buffers 4 6000k

Вроде как должно хватать. Но нет, стал получать ошибку 400 (Bad Request), что согласно документации Nginx означает «поле заголовка запроса превышает размер одного буфера».

Подскажите, пожалуйста, что нужно донастроить, чтобы проблема исчезла?

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

Не пропустите также:

  • Как найти попутку в москву
  • Как составить соглашение на алименты родителям
  • Батарея не показывает заряд как исправить
  • Как составить справку 3 ндфл для налогового вычета за лечение
  • Что делать если меренга не взбивается как исправить

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

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