Nginx 502 "upstream sent too big header": how to fix it

Nginx logs "upstream sent too big header while reading response header from upstream" and answers 502 Bad Gateway when the response headers from your application (PHP-FPM, a container, another proxy) do not fit in the single buffer nginx reserves for them. That buffer is one memory page by default, 4 KB on most Linux servers. The fix is to raise fastcgi_buffer_size (for PHP-FPM) or proxy_buffer_size (for a reverse proxy) on the nginx layer that logged the error, and then to find out why the headers grew so large.
curl -s -o /dev/null -w '%{size_header}\n'; anything near 4 KB will fail on default settings. Set fastcgi_buffer_size 32k; fastcgi_buffers 16 16k; where nginx talks to PHP-FPM, or proxy_buffer_size 32k; proxy_buffers 8 16k; proxy_busy_buffers_size 64k; where nginx proxies to another server, run nginx -t and reload. With two nginx layers (a host proxy in front of a container), the one whose log shows the error is the one to change, and after the inner one is fixed the outer one usually fails next. Then cut the headers at the source: big cookie sessions and Laravel's Link preload header are the usual causes.What does "upstream sent too big header" mean?
It means the upstream server sent a status line plus headers that are larger than the buffer nginx uses to read the first part of the response, so nginx treats the response as invalid and returns 502 to the client. The "upstream" is whatever nginx forwards the request to: PHP-FPM over FastCGI, an application server over HTTP, or another nginx.
The nginx FastCGI documentation describes it directly: the buffer for the first part of the response "usually contains a small response header", and if the header exceeds the buffer size, the response is considered invalid. The default is one memory page, which is "either 4K or 8K, depending on a platform". The proxy module has the same rule for proxy_buffer_size. On x86-64 Linux the page size is 4,096 bytes; check yours with getconf PAGESIZE.
A single per-connection buffer (fastcgi_buffer_size, proxy_buffer_size, and the equivalent uwsgi_, scgi_ and grpc_ directives) that must hold the whole status line and every response header at once. The body can spill into further buffers or a temporary file; the headers cannot.
Three things it is not. It is not about the request: oversized request headers or cookies sent by the browser give a 400 "Request Header Or Cookie Too Large", which is controlled by large_client_header_buffers. It is not about the body: a 5 MB HTML page passes through the same 4 KB header buffer without trouble. And turning buffering off does not help: with proxy_buffering off nginx still reads the headers into a buffer of proxy_buffer_size.
How do you confirm it is this error?
Look for the exact line in the nginx error log of the server that returned the 502, then measure the response headers of the failing URL with curl. A 502 has several possible causes, and the log line tells them apart.
# nginx installed on the host
sudo grep "too big header" /var/log/nginx/error.log | tail -n 3
# nginx in Docker (the official image sends its error log to stderr)
docker compose logs webserver 2>&1 | grep "too big header" | tail -n 3
This is the line we got from a stock nginx:alpine container (nginx 1.31.8) in front of php:8.3-fpm-alpine, when a PHP script sent 4 KB of Set-Cookie headers:
[error] 21#21: *25 upstream sent too big header while reading response header from upstream, client: 172.18.0.4, server: , request: "GET /index.php?kb=8 HTTP/1.1", upstream: "fastcgi://172.18.0.2:9000", host: "127.0.0.1"
Note the upstream: field. fastcgi:// means this nginx talks to PHP-FPM and needs the fastcgi_ directives; http:// means it proxies to another HTTP server and needs the proxy_ directives.
Measure the headers
The browser cannot show you the headers of a 502, because nginx discarded them. Ask the backend directly, bypassing the layer that fails, and count the bytes:
# total header bytes of one response (HTTP/1-style)
curl -s -o /dev/null -w '%{size_header}\n' http://127.0.0.1:8080/login
# the headers themselves, largest first
curl -s -o /dev/null -D - http://127.0.0.1:8080/login | awk '{ print length($0), $1 }' | sort -rn | head
Use GET, not curl -I: some applications answer HEAD with different headers. Repeat the request with the cookies of a logged-in session (-b 'laravel_session=…'), because the largest headers often appear only after login or on one specific page. If the total is close to or above 4,096 bytes, you have found the cause.
| Error log line | Status | What it usually means |
|---|---|---|
| upstream sent too big header while reading response header from upstream | 502 | Response headers larger than *_buffer_size |
| connect() failed (111: Connection refused) while connecting to upstream | 502 | Nothing listens at the upstream address (backend down, or a stale container IP) |
| upstream prematurely closed connection while reading response header from upstream | 502 | The backend process died or closed the connection mid-request |
| upstream timed out (110: Connection timed out) while reading response header from upstream | 504 | Backend too slow; a timeout problem, not a buffer one |
As of November 2026, nginx 1.31.8. The first two lines were reproduced in our test setup; the others are standard nginx messages.
What makes response headers that big?
Almost always one of four things: cookies, Link preload headers, tokens, or debugging headers. A typical response without them is well under 1 KB, so 4 KB takes something that grows.
- Cookie-based sessions. With Laravel's
cookiesession driver, sessions "are stored in secure, encrypted cookies" (Laravel docs). Everything you put in the session, including flash data and old form input, is encrypted and sent back asSet-Cookieon every response. Encryption and base64 make it bigger than the data itself. Browsers only have to accept "at least 4096 bytes per cookie" (RFC 6265, section 6.1), so a single cookie session can approach the default nginx buffer on its own. - Many Set-Cookie headers. Session, CSRF token, "remember me", consent, A/B test and analytics cookies each add a header with its own
Path,Expires,SameSiteandSecureattributes. - Link preload headers. Laravel's
AddLinkHeadersForPreloadedAssetsmiddleware writes every script and stylesheet the Vite helper preloaded into oneLinkheader (framework source). Laravel's official starter kits add this middleware to the web group (Vue starter kit). A code-split page with 25+ chunks and absolute URLs produces a header of several kilobytes. - Tokens and debug data. JWTs in cookies or custom headers, Content-Security-Policy headers with long allow-lists, and development toolbars that send data in headers.
Because cookies depend on the session and preload headers depend on the page, the error tends to hit only some URLs and only some users. "Works when I click through the app, fails when I reload the page" is a classic sign of the Link header: a single-page app's in-app navigation fetches JSON, while a full page load returns HTML with every preloaded chunk listed.
fastcgi_buffer_size or proxy_buffer_size: which one do you change?
Change the module that matches the upstream: in the log line: fastcgi_buffer_size where nginx passes requests to PHP-FPM with fastcgi_pass, and proxy_buffer_size where it forwards them with proxy_pass. Changing the other one does nothing.
| Directive | Used with | Default (bytes) | Value we use |
|---|---|---|---|
fastcgi_buffer_size | fastcgi_pass (PHP-FPM) | 4k or 8k (one page) | 32k |
fastcgi_buffers | fastcgi_pass | 8 × 4k or 8k | 16 16k |
fastcgi_busy_buffers_size | fastcgi_pass | 8k or 16k | leave default unless nginx -t complains |
proxy_buffer_size | proxy_pass (HTTP upstream) | 4k or 8k (one page) | 32k |
proxy_buffers | proxy_pass | 8 × 4k or 8k | 8 16k |
proxy_busy_buffers_size | proxy_pass | 8k or 16k | 64k |
Defaults from the nginx FastCGI and proxy module documentation, as of November 2026.
For PHP-FPM:
location ~ \.php$ {
fastcgi_pass php:9000;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# Response headers up to 32 KB instead of one 4 KB page
fastcgi_buffer_size 32k;
fastcgi_buffers 16 16k;
}
For a reverse proxy:
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_buffer_size 32k;
proxy_buffers 8 16k;
proxy_busy_buffers_size 64k;
}
Why raising only the buffer size fails nginx -t
If you add only proxy_buffer_size 16k (or fastcgi_buffer_size 32k) and keep the default *_buffers 8 4k, the configuration test refuses to start. We got exactly this:
nginx: [emerg] "proxy_busy_buffers_size" must be less than the size of all "proxy_buffers" minus one buffer in /etc/nginx/nginx.conf:32
nginx: configuration file /etc/nginx/nginx.conf test failed
The reason is in the documentation of proxy_busy_buffers_size: by default it is limited by the size of two buffers set by proxy_buffer_size and proxy_buffers. Raising the header buffer to 16k raises the default busy size to 32k, which is more than the 8 × 4k = 32k of body buffers minus one buffer. Raise proxy_buffers with it (8 16k passes), and if you set proxy_busy_buffers_size explicitly, keep it below the total of proxy_buffers minus one buffer: with 4 × 16k, 32k passed and 64k failed with the same message. The FastCGI module gives the same error with fastcgi_ names. Note that the message points at nginx.conf, not at the file you edited.
How large is safe?
Large enough for your measured headers with headroom, not more. These buffers are allocated per connection: the header buffer for every proxied request, the others as the response body needs them. 32k covers any sane application with room to spare. If you need 64k or more, something is producing headers that browsers and CDNs will struggle with too, and the fix belongs in the application.
Two nginx layers: which one needs the change?
The layer whose error log contains the line. In a common Docker setup, nginx on the host terminates HTTPS and proxies to an nginx container, which passes PHP requests to PHP-FPM. Both layers have their own 4 KB default, and both return 502.
We built that chain from stock images (host-style proxy → nginx:alpine → php:8.3-fpm-alpine) and made the PHP script send a growing number of 1 KB Set-Cookie headers:
| Extra headers (KB) | Inner nginx, FastCGI default | Inner nginx, fastcgi_buffer_size 32k | Outer proxy, default (inner at 32k) | Outer proxy, proxy_buffer_size 32k |
|---|---|---|---|---|
| 3 | ✓ 200 | ✓ 200 | ✓ 200 | ✓ 200 |
| 4 | ✗ 502 | ✓ 200 | ✗ 502 | ✓ 200 |
| 10 | ✗ 502 | ✓ 200 | ✗ 502 | ✓ 200 |
| 31 | ✗ 502 | ✓ 200 | ✗ 502 | ✓ 200 |
| 33 | ✗ 502 | ✗ 502 | ✗ 502 | ✗ 502 |
Measured on 16 November 2026, nginx 1.31.8, PHP 8.3 FPM, 4,096-byte memory page. A response with 6 KB of extra cookies measured 6,346 header bytes with curl.
Two practical lessons follow. First, fixing the inner layer moves the failure outward: after we raised the FastCGI buffer, the same requests failed at the outer proxy with upstream: "http://…" in its log, so the browser saw the same 502. Second, the outer layer passes on whatever the inner one returns, so if both are too small, only the inner log shows the error until the inner one is fixed. Check both logs every time you test.
ℹ️ Note: Load balancers and CDNs in front of nginx have their own header limits that you cannot always change. That is one more reason to fix the headers at the source rather than raise buffers on every hop.
How do you shrink the headers at the source?
Store sessions on the server, send fewer preload links and stop putting data into cookies. Bigger buffers make the 502 go away; smaller headers make every request cheaper and keep you clear of limits further down the chain.
Move sessions out of the cookie
In Laravel, switch the session driver from cookie to redis or database. The browser then keeps only the session ID.
# .env
SESSION_DRIVER=redis # or: database (needs the sessions table)
php artisan config:clear
Switching drivers logs everyone out once, because existing sessions live in the old store. With the database driver, make sure the sessions table exists (php artisan make:session-table and php artisan migrate on Laravel versions that don't ship it).
Cap the Link preload header
From Laravel 12, the middleware takes a limit: AddLinkHeadersForPreloadedAssets::using(8) lists only the first 8 assets (source). Nothing else changes: the @vite directive still writes a <link rel="modulepreload"> tag in the HTML for every chunk.
// bootstrap/app.php
use Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets;
->withMiddleware(function (Middleware $middleware) {
$middleware->web(append: [
AddLinkHeadersForPreloadedAssets::using(8),
]);
})
On Laravel 10 and 11 the middleware has no using() method. There you can remove it from the web group (the HTML preload tags remain) or upgrade.
Audit the cookies
- Remove cookies nobody reads any more, and stop setting the same cookie on every response when its value has not changed.
- Keep tokens out of cookies where you can, or keep their claims short; a JWT carrying user profile data is a header problem waiting to happen.
- Set third-party scripts' cookies on the client side or on a separate subdomain if they are not needed by the server.
✅ Advantages of fixing the source
- Fixes every layer at once, including CDNs you don't control
- Smaller requests and responses on every page view
- No per-connection memory increase on the proxy
❌ Considerations
- Changing the session driver logs users out once
- Takes a deploy, while a buffer change takes a reload
- Third-party cookies may be outside your control
How do you apply and verify the change?
Edit the configuration, run nginx -t, reload, and repeat the request that failed while watching the log. A reload applies new settings without dropping open connections.
- Test the configuration
sudo nginx -ton the host, ordocker compose exec webserver nginx -tin a container. Fix any[emerg]before going further. - Reload
sudo systemctl reload nginx(orsudo nginx -s reload); in Docker,docker compose exec webserver nginx -s reload. - Confirm the running configuration
nginx -Tprints the configuration nginx actually loaded.docker compose exec webserver nginx -T | grep -n buffermust show your new values, at the level you expect. Afastcgi_buffer_sizein a nestedlocationoverrides the one inserverorhttp. - Repeat the failing request
Use the same URL and cookies as before; expect 200, and no new "too big header" line in either layer's log.
⚠️ Warning: In Docker, a configuration file mounted on its own (./default.conf:/etc/nginx/conf.d/default.conf) is bound to the file's inode. Tools that save by writing a new file and renaming it, such assed -i, leave the container reading the old version: in our test,nginx -tand a reload succeeded while the container still had no buffer lines. Check withnginx -T, and restart the container (docker compose restart webserver) if the change is missing.
The same fix in NetSendo
NetSendo, a self-hosted email marketing platform built on Laravel, hit this error in its message editor and fixed it at both ends in version 2.2.1 (7 November 2026). According to the changelog, a full page load of the editor answered 502 because the Link header listed about 27 chunks and, with the cookies, pushed the response headers past nginx's 4 KB FastCGI buffer; you can read the summary in the 2.2.1 release post.
- The application now uses
AddLinkHeadersForPreloadedAssets::using(8), which, per the changelog, keeps each page's headers at about 2 KB. This ships in the Docker image. docker/nginx/default.confnow setsfastcgi_buffer_size 32kandfastcgi_buffers 16 16k. Existing installations keep their copy of that file until they replace it, so compare it with the current one in the repository after an update.- Sessions use Redis by default (
SESSION_DRIVER=redisin.env.example), so the session cookie holds only an ID. - The host reverse proxy described in the configuration docs uses nginx's default proxy buffers. With 2 KB headers that is enough; if its log ever shows "too big header", add the three
proxy_lines shown above.
A different 502 after a NetSendo update, with "connect() failed (111: Connection refused)" in the log, was a stale container address and was fixed in version 2.11.1. New installs follow the quick start.
🎯 Expert tips
fastcgi:// or http:// in the log line tells you which directive family to change before you touch anything.
Anonymous requests often carry half the cookies. Copy the session cookie from the browser and repeat the curl measurement with -b.
Fixing the inner nginx moves the 502 to the outer proxy. Tail both error logs while you test.
Add a curl check of %{size_header} for your heaviest page to your monitoring and alert above about 75% of the buffer, so a new cookie or a bigger bundle doesn't surprise you in production.
Frequently asked questions
What causes upstream sent too big header in nginx?
The upstream (PHP-FPM, an app server or another proxy) sent response headers larger than the buffer nginx uses to read them, one memory page or 4 KB by default. Large or numerous cookies, cookie-based sessions and long Link preload headers are the usual causes.
Should I change fastcgi_buffer_size or proxy_buffer_size?
Look at the upstream field in the error log line. fastcgi:// means the nginx talks to PHP-FPM, so change fastcgi_buffer_size and fastcgi_buffers; http:// means it proxies, so change proxy_buffer_size, proxy_buffers and proxy_busy_buffers_size.
What is a safe value for proxy_buffer_size?
32k is enough for almost any application, together with proxy_buffers 8 16k and proxy_busy_buffers_size 64k. Measure your real headers first; if you need 64k or more, fix the application instead.
Why does nginx -t fail after I increase proxy_buffer_size?
Raising the header buffer also raises the default proxy_busy_buffers_size, which must stay below the total of proxy_buffers minus one buffer. Increase proxy_buffers at the same time, for example to 8 16k.
Does proxy_buffering off fix upstream sent too big header?
No. Even with buffering off, nginx reads the response headers into a buffer of proxy_buffer_size, so the header limit stays the same.
Sources
- nginx: ngx_http_fastcgi_module
- nginx: ngx_http_proxy_module
- nginx: large_client_header_buffers (ngx_http_core_module)
- Laravel framework: AddLinkHeadersForPreloadedAssets middleware (12.x)
- Laravel Vue starter kit: bootstrap/app.php
- Laravel documentation: HTTP Session
- RFC 6265: HTTP State Management Mechanism (section 6.1, limits)
- NetSendo CHANGELOG (2.2.1: message editor 502 fix)
Run email marketing on your own server
NetSendo installs with Docker Compose and ships the nginx settings described above.




