HTTP response status code 431 Request Header Fields Too Large is returned by the server to indicate that the HTTP headers are too large. This may indicate the total size used by all HTTP headers or instead, only that certain HTTP headers are too big.
Usage
When the 431 Request Header Fields Too Large status code is received, the server is refusing to process the HTTP request because there is too much data specified by the HTTP headers.
Depending on the server, this may refer to the total length of HTTP headers combined or instead, specific ones. In either case, the client may have the option to remove one or more HTTP headers and try the HTTP request again. One possible solution for limiting the number of HTTP headers is to cut or reduce the Cookies that are being transmitted.
Note
Search engines like Google will not index a URL with 431 Request Header Fields Too Large response status, and consequently, URLs that have been indexed in the past but are now returning this HTTP status code will be removed from the search results.
Example
In the example, the client requests a resource and the server responds with the 431 Request Header Fields Too Large status code because the combination of two very large cookie values exceeds the maximum limit set by the server for HTTP headers.
Request
GET /tech-news HTTP/1.1
Host: www.example.ai
Cookie: first_cookie=<very_long>; second_cookie=<long again!>
Response
HTTP/1.1 431 Request Header Fields Too Large
Content-Type: text/html
Content-Length: 183
<html>
<head>
<title>Request Headers Too Long</title>
</head>
<body>
<p>Your request headers are too long. Try retrying the request without cookies.</p>
</body>
</html>
Code references
.NET
HttpStatusCode.RequestHeaderFieldsTooLarge
Rust
http::StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE
Rails
:request_header_fields_too_large
Go
http.StatusRequestHeaderFieldsTooLarge
Symfony
Response::HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE
Python3.5+
http.HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE
Apache HttpComponents Core
org.apache.hc.core5.http.HttpStatus.SC_REQUEST_HEADER_FIELDS_TOO_LARGE
Angular
@angular/common/http/HttpStatusCode.RequestHeaderFieldsTooLarge
Takeaway
The 431 Request Header Fields Too Large status code is a client error that is sent by the server when the client sends an HTTP request with too much data in the HTTP headers. If the HTTP request can be reduced in size while still making sense, then the HTTP request can be resubmitted with the smaller sized HTTP headers.
See also
- Cookies
- RFC 6585
Last updated: June 2, 2022
Did you just try to visit a website only to be met by the HTTP error 431 message? Or, maybe you have your own website and you’re getting complaints from visitors that they see this error when visiting your site?
HTTP status codes like the 431 error can be frustrating because they get in the way of the website that you want to interact with. Thankfully, though, the error code provides you with the information that you need to fix it in the form of those three numbers – 431.
In this post, you’ll learn what this specific error means and what some of the common causes are. Then, we’ll share four troubleshooting steps that you can follow to fix the problem, whether you’re experiencing it on someone else’s website or your own website.
Check Out Our Video Guide to Fixing the 431 Error
What Is HTTP Error 431?
Before we can talk about the HTTP error 431 specifically, we first need to talk about what HTTP is and where these errors come from.
When you visit a website, your web browser needs a way to communicate with the webserver behind that website. It does this using HTTP, which stands for Hypertext Transfer Protocol.
Your web browser sends an HTTP request to the server for certain information – e.g. the website’s code or an image file. Then, the server sends an HTTP response back to the browser.
Along with these requests and responses, browsers and servers also include HTTP status codes, which are numerical codes like 431.
There are tons of different status codes. In fact, we have an entire guide on HTTP status codes. Some HTTP status codes indicate that everything is functioning normally. However, many HTTP status codes indicate some type of error.
As you can probably guess, the HTTP 431 message is one of the error codes. The number 431 indicates the specific HTTP error, which is “Request Header Fields Too Large.”
Essentially, this means that the HTTP request that your browser is making to the server is too large. Or, another way of phrasing it is that the request is too long.
This can happen because the total size of the request headers is too large or it can happen because a single header field is too large.
Because your browser is making a request that is too large/long, the server drops/denies the request instead of delivering the HTTP response that your browser was expecting.
Because your browser doesn’t receive the needed response, it’s unable to render the webpage and shows the HTTP error 431 message instead.
Did you just try to visit a website only to be met by the HTTP error 431 message? This post is for you 👀Click to Tweet
What Causes a 431 Request Header Fields Too Large Error?
In general, HTTP error codes can indicate a problem in two different areas:
- Server-side – there’s something going wrong in the webserver that’s triggering the error code.
- Client-side – there’s something going wrong in the web browser that’s triggering the error.
The HTTP error 431 is a client-side HTTP error. That means the cause of the problem is somewhere in your web browser (because your web browser is the one making the request with large headers). That also means that you’ll need to apply most fixes by adjusting your web browser.
However, the root cause isn’t always your browser’s fault. Sometimes the way that the website is coded can cause your browser to make large requests.
Typically, the HTTP error 431 is caused by issues with cookies, long referrer URLs, or just the total size of the request headers.
If you’re trying to visit someone else’s website, you can try to eliminate these causes by adjusting your web browser.
If you have your own website and you’re trying to diagnose why your site’s visitors are seeing the HTTP error 431, you might need to dig into your site’s code to make it less likely to cause your site’s visitors to have large requests. For example, you might need to adjust how your site uses cookies in visitors’ browsers or configure your server to accept larger requests.
How To Fix HTTP Error 431 (4 Methods)
Now that you know what the HTTP Error 431 Request Header Fields Too Large message means and some of its causes, let’s get into how you can fix this error.
1. Clear Your Cookies and Browser Cache
Pretty much all websites use cookies to identify and store information about individual users. For example, if you log into a website, that website will use a cookie to remember that you’re logged in so that you don’t need to log in again on every single visit.
To learn more about cookies, check out our guide to cookies and PHP sessions.
However, if there are too many cookies, that can lead to large HTTP request headers, which can trigger the HTTP Error 431 Request Header Fields Too Large message.
One common fix, therefore, is to clear the cookies for the site where you’re experiencing issues. Most popular browsers make this pretty easy to do – we’ll show you below.
Here’s how to clear browser cookies in Chrome:
- Enter the following in your browser address bar – chrome://settings/content/all.
- Search for the URL of the site where you’re experiencing issues.
- Click the trash can icon to delete all of the cookies and site data for that site.
The basic method above should also work for other Chromium-based web browsers, such as Brave, Edge, Vivaldi, Opera, and others. However, you’ll need to go through the settings area rather than pasting in the URL.
To clear cookies for a specific site in Safari, follow these instructions:
- Open the Preferences area (Safari > Preferences).
- Select the Privacy tab.
- Click Manage Website Data.
- Search for and select the site where you’re experiencing issues.
- Click the Remove button once you’ve selected the site.
To clear cookies for a specific site in Firefox, follow these instructions:
- Enter the following in your Firefox browser address bar – about:preferences#privacy.
- Scroll down and find the Cookies and Site Data section.
- Click the Manage Data button in that section.
- Search for and select the site where you’re experiencing issues.
- Click the Remove Selected button once you’ve selected the site.
2. Shorten or Remove URL Query Parameters
Trying to visit a site using URLs with long query parameters can also trigger the HTTP error 431.
Query parameters are the part of a URL that comes after the “main” URL. They’re used to pass additional information to the server, but they aren’t actually required to access the page in most cases.
For example, many sites use UTM parameters to track conversions. Here’s an example of a base URL – https://yoursite.com/ — with some additional query parameters:
https://yoursite.com/?utm_source=Facebook&utm_medium=CtW&utm_campaign=PC&fbclid=IwAR3ph8rkY1UfPOzhbrqPWBGqLXFsFeAP48otBX1F0Ao2Y1RYydAJqms_RQU
To see if this is the problem, delete the question mark and everything that comes after it (the bolded portion above). Then, try revisiting the newly cleaned URL and see if the error disappears.
3. Shorten/Edit Your Code (if Writing Custom Code)
These next two tips won’t help if you’re experiencing the error on someone else’s website. But if you’re experiencing the error on your own site (or if your visitors are complaining of experiencing the error), then these tips can help address the root cause.
The first option is to dig into your site’s code and check if your code is generating large request headers. That is, whether your code is forcing visitors’ browsers to send large requests.
These errors are especially common when working with JavaScript. If you check out StackOverflow, you’ll see that most of the people experiencing this error are using technologies such as AngularJS, React, Node.js, etc.
For example, your Node.js app could be asking for more information than is needed, which is generating unnecessarily large request headers. Similarly, remember that spaces in your code count towards the size of the request, so that can be another “invisible” source of large requests.
In some cases, you can also adjust the maximum request size at the server level by editing your server’s configuration code. For example, if you’re using React, you can adjust the max header size in the package.json file – look for this line of code:
"start": "react-scripts --max-http-header-size=1024 start",
4. Adjust Cookie Settings (if Your Site Triggers Errors for Users)
Another way that your site could trigger the HTTP error 431 is the way in which it’s using cookies.
For example, if you’re setting lots of cookies in users’ browsers, that could trigger the error. This is one of the reasons why clearing a site’s cookies is one of the potential fixes.
To avoid this, make sure that you’re not setting too many cookies by accident. This will require digging into your site’s code or hiring an expert with the qualifications to do so.
HTTP status codes like the 431 error can be frustrating because they get in the way of the website that you want to interact with. 😅 This guide is here to help 🚀Click to Tweet
Summary
The HTTP Error 431 Request Header Fields Too Large error is a client-side error that appears when your web browser makes a request to the server with headers that are too large and/or long.
Because the request is too large, the server rejects the request, which is why your web browser displays the HTTP Error 431 message instead of the content that you were expecting.
If you’re experiencing this error when visiting another site, the most common fix is to clear your browser’s cookies for that site. You should also make sure that the URL isn’t too long because of query parameters.
If you’re experiencing this error when visiting your own site (or your visitors are complaining about this error), you’ll likely need to dig into your code to make sure you aren’t generating large request headers or setting too many cookies. In some cases, you might also be able to increase the maximum request header size at the server level by editing your server’s configuration files.
To learn more about HTTPS status codes in general, check out our full guide to HTTP status codes. We also have a number of posts focused on fixing other common HTTP errors, including Internal Server, Bad Requests, Bad Gateway, Not Found Errors.
Updated: 02/14/2023 — 11:19
Time to read: 4 minutes
HTTP error 431 returns the status code: Request header fields too large
You’ve tried to look at content on your own website, and you’ve hit an error. Read through it, and you’ll know that the system thinks «request header fields too large.» But you have no idea what that means.
HTTP errors are meant to give you information about the communication between your device and a website server. But the codes were written for developers, not average people. And even experts can be confused by obscure codes like this one.
Fixing HTTP error 431 is relatively easy once you know what to look for. We’ll walk you through the steps.
Understand the HTTP Language
The acronym HTTP stands for «hypertext transfer protocol,» which was established in 1991. Think of this protocol as the language of requests and responses between devices and servers.
Each time you visit a website, a predictable set of steps happens.
- Browser request: You need data or information from the web server to visit the page.
- Data movement: Buried within that request is information about you, your browser, and more.
- The server’s response: You’re either given access, or you get a code that explains the denial.
Requests are sometimes called «headers.» The HTTP protocol doesn’t specify how long or big these pieces of data can be. But some servers limit size for security reasons.
And that’s where HTTP error 431 comes in.
Unpacking HTTP Error 431
Several types of HTTP errors exist, and they’re numerically grouped. All of the codes in the 400 level involve user errors. These aren’t problems that technically originate with the website or your server. Instead, they involve some kind of request from the user that a website’s server can’t process.
Error 431, which officially says «Request header fields too large,» means the server has dropped the request. The header sent by the user is either too long or too large, and the server denies it.
Web developers can request all kinds of data from users. You might ask for information about these things:
- Preferred languages
- Credentials
- Hosts
- Referring sites
If you ask for too much information, or the data you get back is somehow chunky or lengthy, your user will hit this error code. The page won’t load until the problem is resolved.
Fix Error 431 in 4 Steps
Every HTTP error 431 message is different, and your website could throw up this barrier for reasons that don’t apply to other businesses you know. But for most companies, the problem comes down to one of two factors.
Your visitors could see the code due to cookies or the referring URL is too long.
Try fixing the problem by:
- Eliminating the referrer URL. If you know you have active links on a site with a very long URL, eliminate this query before allowing access.
- Walking through your code. Spaces in your code are applied toward character limits, and they’re not always needed. You could also ask for data you never use or need, which could force users up against your character limits.
- Examining your cookie settings. If you have authorization code mistakes, you could be setting multiple cookies for your users, and that could cause unwelcome HTTP errors.
- Accepting more cookies. If cookies are at the crux of your problem, let more in. Cookies do come with security vulnerabilities, so proceed with care. But if eliminating an error code at all costs is your goal, accepting more cookies could be helpful.
You may need to talk with your server host before making some changes. If you adjust your code to accept more data, but your server doesn’t agree, your users could hit a similar HTTP code involving server access. An open conversation before you adjust code is always wise.
Get Help From Okta
If HTTP errors plague you, we can help. We’ll walk through the problems with you, and we’ll figure out how to give your users access without compromising your security. Contact us to find out more.
References
Brief History of HTTP. High Performance Browser Networking. O’Reilly.
Additional HTTP Status Codes. (April 2012). Internet Engineering Task Force.
Risk Associated With Cookies. (November 2013). Infosec.
5 Tips to Avoid Potential Dangers of Cookies. (November 2020). C Online Mag.
431 – код ответа HTTP-заголовка, если точнее, то один из них. Есть много кодов, каждый указывает на определенную проблему. По цифре в сообщении довольно просто определить, какая именно неполадка стала причиной проблемы. В результате любого из кодов не получится загрузить страницу в браузере или любой сайт в целом. Сразу нужно оговориться, что это не всегда зависит от клиента, может быть виноват и сервер.
Суть проблемы
Сообщение HTTP 431 Request Header Fields Too Large само по себе говорит о том, что был отправлен заголовок со слишком большой длиной. В запросе может быть либо один большой заголовок, либо несколько. Чтобы сайт заработал, нужно сократить длину заголовка. Однако его формирование выполняет сайт, а не пользователь, поэтому прямо доступа к редактированию HTTP у нас нет. В значительной части случаев проблема в том, что разработчик неправильно что-то настроил.
Как исправить ошибку 431?
Все, что нужно сделать – очистить кэш и куки в браузере. Первый вариант заключается в том, чтобы удалить все данные этого рода для разных сайтов за определенный промежуток времени. Просто нажимаем CTRL + SHIFT + DEL и увидим окно со всем необходимым. Другой подход сводится к чистке кэша конкретного сайта, если сбой касается только его.
Как очистить cookie сайта:
- Переходим в «Настройки» браузера в раздел «Конфиденциальность и безопасность».
- Выбираем вкладку «Настройки сайтов», а затем переходим сюда – «Файлы сookie и данные сайтов».
- Кликаем на «Все файлы cookie и данные сайтов».
- Ищем тот веб-ресурс, который отправляет назад ошибку HTTP 431.
- Жмем на крестик возле всех сохраненных данных сайта.
- Повторяем запрос на веб-ресурс.
Если в результате чистки куки ошибка HTTP 431 Request Header Fields Too Large не перестанет появляться, сбой спровоцирован какими-то ошибками со стороны сервера. Можно дополнительно проверить, работает ли сайт в режиме Инкогнито и в другом браузере. Обычно нужно просто подождать, пока веб-сайт восстановится.
Время на прочтение
2 мин
Количество просмотров 13K
На рассмотрение в IETF поданы спецификации новых кодов состояния HTTP, которые более точно описывают некоторые типичные ситуации.
428 Precondition Required 429 Too Many Requests 431 Request Header Fields Too Large 511 Network Authentication Required
Код состояния 428 (precondition required) означает, что серверу требуются условия выполнения запроса. Это типичная ситуация, когда клиент получает данные по GET, модифицирует их и отправляет назад на сервер через PUT, но к тому времени они уже были модифицированы другим клиентом, из-за чего возникает конфликт. Требуя обусловленного запроса, сервер защищается от возникновения конфликта. При этом обязательно должны быть указаны условия для корректной отправки данных на сервер.
HTTP/1.1 428 Precondition Required
Content-Type: text/html
<html>
<head>
<title>Precondition Required</title>
</head>
<body>
<h1>Precondition Required</h1>
<p>This request is required to be conditional;
try using "If-Match".</p>
</body>
</html>
Код состояния 429 (too many requests) означает, что пользователь отправил слишком много запросов в заданный период времени. Ответ должен содержать объяснение нарушенного условия и может содержать заголовок Retry-After с указанием времени, которое нужно подождать перед повтором.
HTTP/1.1 429 Too Many Requests
Content-Type: text/html
Retry-After: 3600
<html>
<head>
<title>Too Many Requests</title>
</head>
<body>
<h1>Too many Requests</h1>
<p>I only allow 50 requests per hour to this Web site per
logged in user. Try again soon.</p>
</body>
</html>
Код состояния 431 (request header fields too large) используется тогда, когда сервер отказывает в обработке запроса из-за того, что один или несколько заголовков в сумме превышают норму. Во втором случае в ответе должно содержаться указание, какой именно заголовок вызвал проблему.
HTTP/1.1 431 Request Header Fields Too Large
Content-Type: text/html
<html>
<head>
<title>Request Header Fields Too Large</title>
</head>
<body>
<h1>Request Header Fields Too Large</h1>
<p>The "Example" header was too large.</p>
</body>
</html>
Код состояния 511 (network authentication required) означает, что нужно выполнить аутентификацию, при этом в ответе должна содержаться инструкция о том, как это сделать, например, с помощью HTML-формы по указанному адресу. Ошибку 511 возвращает не целевой сервер, а прокси, который не пускает пользователя в сеть (например, маршрутизатор в зоне платного Wi-Fi при неавторизованном доступе).
Например, пользователь отправляет HTTP-запрос по TCP на порт 80.
GET /index.htm HTTP/1.1
Host: www.example.com
Логин-сервер возвращает такой ответ.
HTTP/1.1 511 Network Authentication Required
Refresh: 0; url=https://login.example.net/
Content-Type: text/html
<html>
<head>
<title>Network Authentication Required</title>
</head>
<body>
<p>You need to <a href="https://login.example.net/">
authenticate with the local network</a> in order to get
access.</p>
</body>
</html>