Nginx Request Header Fields Too Large
The HTTP 431 status code indicates that the server refused to process a request because its header fields were collectively too large, exceeding the server's configured buffer limits.
Common Causes
- Excessively long cookies, especially authentication tokens.
- Large custom headers added by proxies or application frameworks.
- Default Nginx `client_header_buffer_size` and `large_client_header_buffers` values are too small for the request.
How to Fix
1 Increase Header Buffer Size in Nginx
Adjust the `client_header_buffer_size` (for normal requests) and `large_client_header_buffers` (for requests with very long headers) directives in your Nginx configuration file (`nginx.conf` or a site-specific file).
$ # Edit your nginx config file
sudo nano /etc/nginx/nginx.conf
# Inside the http { } block, add or modify:
http {
client_header_buffer_size 16k;
large_client_header_buffers 4 32k;
...
}
# Test configuration and reload
sudo nginx -t
sudo systemctl reload nginx 2 Debug and Identify Large Headers
Log the request headers to identify which specific header is causing the size overflow. This helps in targeted optimization, such as reducing cookie size.
$ # In your nginx server or location block, add:
server {
location / {
# Log all request headers to a file
set $dump $http_user_agent;
access_log /var/log/nginx/headers.log combined;
...
}
}
# Check the log after reproducing the error
sudo tail -f /var/log/nginx/headers.log 3 Reduce Client-Side Header Size
If the large header is under your control (e.g., an application cookie), reduce its size. For authentication tokens, consider using shorter session identifiers or reference tokens instead of storing all data in the cookie.
$ # Example: In a web application framework, configure session settings.
# For example, in a Node.js/Express app using express-session:
const session = require('express-session');
app.use(session({
secret: 'your-secret',
cookie: { maxAge: 60000, httpOnly: true },
// Avoid storing large objects in the session cookie
resave: false,
saveUninitialized: false
}));