全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-20 7 分钟 ✍️ juanwangdev

nginx http配置段

http 配置段定义 Nginx 处理 HTTP 请求的行为,是 Web 服务的核心区域。

基础配置

nginx
http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 65;
    
    server {
        # ...
    }
}

MIME 类型

nginx
include /etc/nginx/mime.types;
default_type application/octet-stream;
指令说明
include mime.types引入 MIME 类型映射文件
default_type无法识别类型时的默认值

文件传输优化

nginx
sendfile on;
tcp_nopush on;
tcp_nodelay on;
指令作用
sendfile on启用零拷贝,内核直接传输文件
tcp_nopush on配合 sendfile,数据满包后发送
tcp_nodelay on禁用 Nagle 算法,小包立即发送

连接保持

nginx
keepalive_timeout 65;
keepalive_requests 100;
keepalive_disable msie6;
指令说明
keepalive_timeout长连接超时时间(秒)
keepalive_requests单连接最大请求数
keepalive_disable对特定浏览器禁用 keepalive

请求体限制

nginx
client_max_body_size 10m;
client_body_buffer_size 16k;
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;
指令说明
client_max_body_size请求体最大大小,超过返回 413
client_body_buffer_size请求体缓冲区大小
client_header_buffer_size请求头缓冲区大小
large_client_header_buffers大请求头缓冲区(数量 大小)

超时设置

nginx
client_body_timeout 12;
client_header_timeout 12;
send_timeout 10;
指令说明
client_body_timeout读取请求体超时时间
client_header_timeout读取请求头超时时间
send_timeout发送响应超时时间

压缩配置

nginx
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 256;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;

日志配置

nginx
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent"';

access_log /var/log/nginx/access.log main;

虚拟主机引入

nginx
http {
    # 全局配置...
    
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

完整示例

nginx
http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    client_max_body_size 10m;
    
    gzip on;
    gzip_types text/css application/javascript;
    
    log_format main '$remote_addr - $request - $status';
    access_log /var/log/nginx/access.log main;
    
    include /etc/nginx/conf.d/*.conf;
}

注意事项

  • http 段内可包含多个 server 段
  • http 段的配置会被子 server 段继承
  • sendfile 仅对静态文件有效,动态内容不受益
  • client_max_body_size 影响文件上传大小限制

要点总结

  • http 配置段定义 MIME 类型、传输优化、连接保持、请求限制等
  • sendfile + tcp_nopush + tcp_nodelay 组合提升静态文件传输性能
  • keepalive_timeout 控制长连接保持时间
  • client_max_body_size 限制请求体大小,影响文件上传
  • gzip 压缩减少传输体积,提升页面加载速度
  • http 段配置被子 server 段继承

📝 发现内容有误?点击此处直接编辑

← 上一篇 nginx events配置段
下一篇 → nginx include指令
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库