NGINX中收到HTTP请求大小相关的错误,以下典型错误及相关解决方案。
nginx 配置文件 nginx.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| user root;
worker_processes 1;
error_log logs/error.log debug;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
#large_client_header_buffers 4 16k;
server {
listen 80;
server_name localhost;
location / {
root /root/nginx-quic/html;
index index.html index.htm;
}
}
}
|
1. 请求头超长(HTTP 400/414)#
- HTTP 400 (Bad Request):请求头过大,导致无法解析。
- HTTP 414 (URI Too Long):请求行(URI 部分)过长。
模拟请求头超长#
1
| curl -v -H "$(head -c 8192 < /dev/zero | tr '\0' 'A'): value" http://localhost
|
此命令发送一个包含 8192 个字符的请求头字段, 返回结果
1
2
3
4
5
6
| < HTTP/1.1 400 Bad Request
< Server: nginx/1.25.4
< Date: Sat, 23 Nov 2024 13:26:23 GMT
< Content-Type: text/html
< Content-Length: 233
< Connection: close
|
检查 error.log,通常会看到类似以下错误:
1
| 2024/11/23 21:26:23 [info] 1494546#0: *1 client sent too long header line: "AAAAAAAAAAAAAAAAAAAAA。。。
|
模拟 URI 超长#
1
| curl -v "http://localhost/$(head -c 10000 < /dev/zero | tr '\0' 'a')"
|
此命令发送一个包含 10000 个字符的uri, 返回结果
1
2
3
4
5
6
| < HTTP/1.1 414 Request-URI Too Large
< Server: nginx/1.25.4
< Date: Sat, 23 Nov 2024 13:28:47 GMT
< Content-Type: text/html
< Content-Length: 177
< Connection: close
|
检查 error.log,通常会看到类似以下错误:
1
| 2024/11/23 21:30:40 [info] 1495051#0: *1 client sent too long URI while reading client request line, client...
|
修复方法#
- 调整
large_client_header_buffers:
1
| large_client_header_buffers 4 16k;
|
2. 请求体超大(HTTP 413)#
- HTTP 413 (Payload Too Large):请求体超过限制。
发送一个大文件(超过限制):#
nginx client_max_body_size 默认值 为 1M:
1
2
| dd if=/dev/zero of=large_file bs=1M count=2
curl -v -X POST -F "file=@large_file" http://localhost
|
- 客户端返回
413 Request Entity Too Large
1
2
3
4
5
6
| < HTTP/1.1 413 Request Entity Too Large
< Server: nginx/1.25.4
< Date: Sat, 23 Nov 2024 14:33:04 GMT
< Content-Type: text/html
< Content-Length: 183
< Connection: close
|
检查 error.log,通常会看到类似以下错误:
1
| 2024/11/23 22:33:04 [error] 1495158#0: *7 client intended to send too large body: 2097366 bytes
|
修复方法:#
1
| client_max_body_size 50m;
|
| 问题类型 | 错误代码 | 配置项 | 解决方法 |
|---|
| 请求头字段或 URI 太长 | 400/414 | large_client_header_buffers | 增加缓冲区大小或数量 |
| 请求体太大 | 413 | client_max_body_size | 增加请求体最大大小限制 |
图片from陳柏濡