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 段继承
📝 发现内容有误?点击此处直接编辑