Nguyên nhân
HTTP 413 "Request Entity Too Large" xảy ra khi request body vượt quá limit được cấu hình. Trong stack có nhiều layer (CDN → Nginx → App), bất kỳ layer nào cũng có thể trả về 413.
Fix trên Nginx
# nginx.conf hoặc trong server block
http {
client_max_body_size 100M; # default là 1M
server {
# Cũng có thể set ở level server hoặc location
location /upload {
client_max_body_size 500M;
}
}
}
nginx -t && nginx -s reload
Fix upstream app
Nếu Nginx đã OK nhưng vẫn 413, check application:
NestJS/Express:
// main.ts
app.use(express.json({ limit: '100mb' }));
app.use(express.urlencoded({ limit: '100mb', extended: true }));
NestJS với @nestjs/platform-fastify:
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({
bodyLimit: 104857600, // 100MB in bytes
}),
);
Debug multi-layer proxy
Check response headers để xác định layer nào trả về 413:
curl -v -X POST https://api.example.com/upload \
-H "Content-Type: application/json" \
-d '{"data": "..."}' 2>&1 | grep -E "(< HTTP|< Server|< X-)"
# < HTTP/2 413
# < server: cloudflare ← Cloudflare đang block, không phải Nginx!
Nếu server header là cloudflare, cần tăng limit ở Cloudflare:
- Cloudflare → Rules → Configuration Rules → Request Body Size
- Mặc định Free plan: 100MB, Enterprise: unlimited
# Nếu server header là nginx
# < server: nginx
# → Fix ở nginx config
# Nếu không có server header hoặc là app framework
# → Fix ở application layer