# HTTP 块配置

URL: https://caijiao.org/nginx/http-block
Source: docs/nginx/http-block.md
Description: 本节详细讲解 Nginx 配置文件中的 http 块，包括 MIME 类型、日志、连接控制、gzip 压缩以及 include 子配置，帮助你理解 nginx.conf 中核心 HTTP 设置。

HTTP 块是 Nginx 配置文件中最核心的部分，用于配置 Web 服务相关参数，如日志、文件传输、请求处理和模块加载。

## 一、http 块基本结构

```nginx
http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    
    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    keepalive_timeout  65;
    gzip            on;

    include /etc/nginx/conf.d/*.conf;
}
````

## 二、核心指令说明

### 1. include

* `include mime.types;`：加载 MIME 类型映射表，决定文件类型响应头
* `include /etc/nginx/conf.d/*.conf;`：加载 conf.d 下的子配置，如虚拟主机
* Debian/Ubuntu 常用 `include /etc/nginx/sites-enabled/*;`

### 2. 日志配置

* **log_format**：定义日志格式
* **access_log**：指定访问日志存放路径与格式
* **error_log**：可在全局块或 http 块设置错误日志级别

### 3. 文件传输与连接控制

* `sendfile on;`：启用高效文件传输
* `keepalive_timeout 65;`：保持客户端长连接时间
* `client_max_body_size 10M;`：限制请求体大小

### 4. gzip 压缩

```nginx
gzip on;
gzip_types text/plain text/css application/javascript application/json;
```

启用 gzip 可压缩响应，提高网络传输效率。

## 三、http 块优化建议

1. 根据业务流量调整 `worker_connections` 与 `keepalive_timeout`
2. 配置访问日志轮转，避免日志文件过大
3. 使用 gzip 压缩，提高前端加载速度
4. 使用 include 模块化配置，便于管理多个站点

---

通过掌握 HTTP 块配置，你可以灵活控制 Nginx 的 Web 服务行为，并结合 server/location 块完成站点部署与请求处理。
