主题
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 块优化建议
- 根据业务流量调整
worker_connections与keepalive_timeout - 配置访问日志轮转,避免日志文件过大
- 使用 gzip 压缩,提高前端加载速度
- 使用 include 模块化配置,便于管理多个站点
通过掌握 HTTP 块配置,你可以灵活控制 Nginx 的 Web 服务行为,并结合 server/location 块完成站点部署与请求处理。