nginx.conf 中的 http 块是 Web 服务基础配置容器,必需包含 include mime.types、default_type、sendfile、keepalive_timeout 和 access_log;推荐补充 charset、client_max_body_size、tcp_nopush/nodelay 及 gzip 等参数以提升稳定性与性能。

在 nginx.conf 中配置 http 块,是启用 Web 服务、反向代理、静态资源托管等功能的基础。它不直接运行,但承载所有 server 和 location 配置,影响整个 HTTP 服务的行为。
http 块必须包含的基础指令
以下几项是实际生效所必需的最小配置组合:
- include mime.types;:加载标准 MIME 类型映射,确保浏览器能正确识别 CSS、JS、图片等资源类型
- default_type application/octet-stream;:当无法匹配 MIME 类型时的兜底响应类型
- sendfile on;:启用内核级零拷贝文件传输,显著提升静态文件(如 HTML、图片)性能
- keepalive_timeout 65;:设置客户端连接保持时间(单位:秒),避免频繁建连开销;生产环境常见值为 30~75
-
access_log /var/log/nginx/access.log main;:开启访问日志,并指定日志格式(需提前用
log_format main {...}定义)
推荐补充的关键参数
这些不是强制项,但几乎每个稳定部署都会加上:
-
charset utf-8;:统一响应字符集,防止中文乱码(尤其配合
index.html或 API 返回文本时) -
client_max_body_size 20m;:限制客户端上传体大小,防恶意大文件请求;单位支持
m(MB)、k(KB) - tcp_nopush on; 和 tcp_nodelay on;:分别优化包发送时机与延迟,常成对启用
-
gzip on; 及配套
gzip_types:启用响应压缩,减少带宽消耗(建议至少包含text/plain text/css application/json)
注意 include 的实际路径和顺序
http 块中常用 include 引入外部配置,例如:
-
include /etc/nginx/conf.d/*.conf;:加载所有以.conf结尾的子配置文件(典型用于按站点拆分) -
include /etc/nginx/sites-enabled/*;:Debian/Ubuntu 系统常用方式,通过软链接管理启用站点 - 注意:被 include 的文件中不能重复定义
http块,只能放server、upstream等子块
一个精简可用的 http 块示例
可直接复制到 nginx.conf 的 http { ... } 区域内:
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
<pre class="brush:php;toolbar:false;">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;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/conf.d/*.conf;}


















