# NGINX 中HTTP请求大小相关配置及解决方案-1
Date: 2024-11-24


NGINX中收到HTTP请求大小相关的错误,以下典型错误及相关解决方案。

nginx 配置文件 nginx.conf

```
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 部分）过长。

####  **模拟请求头超长**

```bash
curl -v -H "$(head -c 8192 < /dev/zero | tr '\0' 'A'): value" http://localhost
```

此命令发送一个包含 8192 个字符的请求头字段, 返回结果

```bash
< 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`，通常会看到类似以下错误：

```plaintext
2024/11/23 21:26:23 [info] 1494546#0: *1 client sent too long header line: "AAAAAAAAAAAAAAAAAAAAA。。。
```

#### **模拟 URI 超长**

```bash
curl -v "http://localhost/$(head -c 10000 < /dev/zero | tr '\0' 'a')"
```

此命令发送一个包含 10000 个字符的uri, 返回结果

```bash
< 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`，通常会看到类似以下错误：

```plaintext
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`：

```nginx
large_client_header_buffers 4 16k;
```

* * *

### **2\. 请求体超大（HTTP 413）**

- **HTTP 413 (Payload Too Large)**：请求体超过限制。

####  发送一个大文件（超过限制）：

nginx `client_max_body_size` 默认值 为 1M：

```bash
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`

```bash
< 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`，通常会看到类似以下错误：

```plaintext
2024/11/23 22:33:04 [error] 1495158#0: *7 client intended to send too large body: 2097366 bytes
```

####   **修复方法**：

- 调整 `client_max_body_size`：

```nginx
client_max_body_size 50m;
```

* * *

#### **总结**

| 问题类型 | 错误代码 | 配置项 | 解决方法 |
| --- | --- | --- | --- |
| 请求头字段或 URI 太长 | 400/414 | `large_client_header_buffers` | 增加缓冲区大小或数量 |
| 请求体太大 | 413 | `client_max_body_size` | 增加请求体最大大小限制 |

 

图片from[**陳柏濡**](https://www.facebook.com/groups/474930279315210/user/100000060530795/?__cft__[0]=AZXqugkxZmTsMKg0Xs6VG6cyLBFepwHKnIi-5_swk-tNf0tsxSLVd_EDvhTqmrTy8tt6FjUVfhVv4rhC9rsd8zh5iwhuDEFpP98UACzpM1AHgf9ThOXRLrswU7zANg1WXWqBTso9nYa6DW2Vg4GGH47WQp9zvcbt-bHfdWUaAma-iAvZrflabAkXcpfS4QUxXl3O5Tq0yR4YmGsYZ4K8EEh9&__tn__=-UC%2CP-R)

