العربية

413 Request Entity Too Large: fixing file uploads behind Nginx

An upload works on your laptop and fails in production with 413. Here is where upload limits actually live, how to raise them safely, and how to handle large files without choking your server.

· 6 min read
413 Request Entity Too Large: fixing file uploads behind Nginx

The upload works on your machine. You deploy, a user picks a 6 MB PDF, and the request dies with 413 Request Entity Too Large. Sometimes the browser shows a CORS error instead, which sends you looking in the wrong place for an hour.

I hit this on a conference platform where speakers upload slides and posters. The fix takes one line. Knowing which line, and how far to raise it without opening a hole, takes a bit more. This is the full map.

Why a 413 Request Entity Too Large error happens

A 413 means some layer between the browser and your code decided the request body is bigger than it allows. Several layers can say no, and each has its own limit:

  • Nginx, through client_max_body_size. The default is 1 MB, which is why so many uploads fail right after deployment.
  • Your app's body parser. Express's express.json() and express.urlencoded() default to 100 KB.
  • Your upload middleware, such as multer, if you set limits.
  • PHP, through upload_max_filesize and post_max_size.
  • Anything in front of Nginx: a CDN, a load balancer, or a second Nginx inside a Docker container. Each one has its own limit, so check your plan.

Locally there is usually no Nginx, so the first and most common limit simply does not exist. That is why it works on your laptop.

Find which layer said no

Do not raise every limit blindly. Find the one that rejected the request.

Open the network tab and look at the response body. An HTML page with "nginx" at the bottom means Nginx rejected it before your app saw anything. A JSON error or a stack trace mentioning PayloadTooLargeError means your Express body parser did it.

The Nginx error log confirms it:

sudo tail -n 50 /var/log/nginx/error.log | grep "too large"

You will see a line like client intended to send too large body: 6291456 bytes.

This also explains the confusing CORS error. When Nginx rejects the request, the response comes from Nginx, not your app, so it carries none of the CORS headers your app normally adds. The browser sees a cross-origin response without those headers and reports CORS. The real problem is the 413 underneath. Your frontend may also crash trying to parse that HTML page as JSON.

Nginx upload size: set client_max_body_size per location

The tempting fix is client_max_body_size 0; in the http block, which disables the check everywhere. Don't. The limit protects you from someone sending gigabytes to your login endpoint.

Keep a small default for the whole site and raise it only where uploads happen:

server {
    server_name example.com;

    # Small default for every route
    client_max_body_size 2m;

    location / {
        proxy_pass http://127.0.0.1:3000;
    }

    # Larger limit only for the upload endpoint
    location /api/uploads {
        client_max_body_size 50m;
        proxy_pass http://127.0.0.1:3000;
    }
}

The directive works in http, server and location blocks, and the most specific one wins. Test and reload:

sudo nginx -t && sudo systemctl reload nginx

Pick the number from a product rule, not a guess. "Slides up to 50 MB" is a rule you can show in the UI and enforce in every layer. If you are setting up the proxy for the first time, my guide on deploying a Node.js app with PM2 and Nginx covers the full server block.

App limits: body parser, multer and PHP

Once Nginx lets the request through, your app gets a vote.

Express body parser. Files should not go through express.json() at all. Send them as multipart/form-data and keep the JSON limit small. If you really need larger JSON, raise it on purpose:

app.use(express.json({ limit: '1mb' }));
app.use(express.urlencoded({ extended: true, limit: '1mb' }));

multer. multer has no file size limit by default, which is its own risk. Set one, write to disk instead of memory, and turn its errors into a proper 413:

const express = require('express');
const multer = require('multer');

const app = express();

const upload = multer({
  dest: '/var/app/uploads-tmp',
  limits: { fileSize: 50 * 1024 * 1024, files: 1 },
});

app.post('/api/uploads', upload.single('file'), (req, res) => {
  res.json({ ok: true, name: req.file.originalname, size: req.file.size });
});

app.use((err, req, res, next) => {
  if (err instanceof multer.MulterError && err.code === 'LIMIT_FILE_SIZE') {
    return res.status(413).json({ error: 'File is too large (max 50 MB).' });
  }
  if (err.type === 'entity.too.large') {
    return res.status(413).json({ error: 'Request body is too large.' });
  }
  next(err);
});

Without that error handler, a multer limit error falls through to Express's default handler and becomes a generic 500, which is harder to debug and useless to the user.

PHP. Two settings matter, and post_max_size must be larger than upload_max_filesize because the whole form, not just the file, counts:

upload_max_filesize = 50M
post_max_size = 55M

The trap: when a request exceeds post_max_size, PHP does not throw a clear error. $_POST and $_FILES simply arrive empty, and your code reports "no file uploaded". Also, PHP-FPM often reads a different php.ini than the command line. Check the path in phpinfo() from the web, not php --ini in the terminal, then restart FPM with your version:

sudo systemctl restart php8.1-fpm

Stream large files instead of buffering them

Raising limits works for files in the tens of megabytes. For hundreds of megabytes or more, how the bytes travel matters more than the number.

By default Nginx buffers the whole request body, writing it to a temp file on disk before passing anything to your app. Your app then often buffers it again. For big files that means double disk writes and long waits before your code even starts. You can let Nginx pass the body through as it arrives:

location /api/uploads {
    client_max_body_size 500m;
    client_body_timeout 120s;
    proxy_request_buffering off;
    proxy_http_version 1.1;
    proxy_pass http://127.0.0.1:3000;
}

proxy_http_version 1.1 matters here: chunked request bodies are still buffered unless HTTP/1.1 is used to talk to the upstream. It is the same family of issue as the SSE buffering fix, just in the other direction.

On the app side, use multer with disk storage or a streaming parser like busboy, and never memoryStorage() for large files. For really big files, consider two better patterns:

  • Direct-to-storage uploads. Your server issues a short-lived signed URL, and the browser uploads straight to object storage. Your server never touches the bytes.
  • Chunked or resumable uploads. The client sends the file in parts, so a dropped mobile connection does not restart a 300 MB upload from zero.

Check the size on the client first

Make the user find out in one second, not after a two-minute upload that ends in an error:

const MAX_BYTES = 50 * 1024 * 1024;
const input = document.querySelector('#file');
const message = document.querySelector('#file-message');

input.addEventListener('change', () => {
  const file = input.files[0];
  if (file && file.size > MAX_BYTES) {
    message.textContent = 'This file is larger than 50 MB. Please choose a smaller one.';
    input.value = '';
  } else {
    message.textContent = '';
  }
});

Add an accept attribute to narrow the file types, and show the limit next to the button before anyone picks a file.

Client checks are for user experience only. Anyone can skip them with a direct request, so the server limits stay. The goal is one number, written once in your config, enforced by Nginx and the app, and shown in the UI.

FAQ

How do I fix 413 Request Entity Too Large in Nginx?

Add client_max_body_size 50m; (or your limit) inside the location that handles uploads, run sudo nginx -t, then reload Nginx. If the error continues, check your app's body parser and any proxy or CDN in front of Nginx.

What is the default client_max_body_size in Nginx?

1 MB. Any request body larger than that gets a 413 unless you raise the limit.

Why does my upload show a CORS error instead of 413?

Nginx rejected the request before it reached your app, so the response is missing the CORS headers your app normally adds. Look in the Nginx error log for "too large body".

Should I set client_max_body_size to 0?

Avoid it. It removes the limit for every route. Keep a small default and raise it only on upload endpoints.


Fighting an upload bug or planning a file-heavy platform? Talk to the editor at ahmed-adil.com.

More from the Supplement