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

nginx核心配置文件结构

Nginx 配置文件的组织方式决定了服务器的行为,下面解析核心配置段的作用与层级关系。

配置文件层级

nginx
# main 段(全局上下文)
worker_processes auto;

events {
    # events 段
    worker_connections 1024;
}

http {
    # http 段
    include mime.types;
    
    server {
        # server 段
        listen 80;
        
        location / {
            # location 段
            root /var/www/html;
        }
    }
}

配置段层级关系

配置段上级下级作用
mainevents, http, mail, stream全局上下文
eventsmain连接处理
httpmainserver, upstream, map, geoHTTP 服务
serverhttplocation, if虚拟主机
locationserverif, limit_except路径匹配
upstreamhttpserver负载均衡
streammainserver四层代理
mailmainserver邮件代理

main 段可配置项

nginx
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events 段

nginx
events {
    worker_connections 1024;
    multi_accept on;
    use epoll;
}

http 段

nginx
http {
    # 基础
    include mime.types;
    default_type application/octet-stream;
    
    # 日志
    log_format main '...';
    access_log /var/log/nginx/access.log;
    
    # 传输优化
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 65;
    
    # 压缩
    gzip on;
    
    # 虚拟主机
    include /etc/nginx/conf.d/*.conf;
}

server 段

nginx
server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    index index.html;
    
    access_log /var/log/nginx/example.access.log;
    error_log /var/log/nginx/example.error.log;
}

location 段

nginx
location / {
    try_files $uri $uri/ =404;
}

location ~ \.php$ {
    fastcgi_pass 127.0.0.1:9000;
}

注意事项

  • 配置段可嵌套,子段继承父段配置
  • 同一层级可存在多个 server 或 location
  • mail 和 stream 段与 http 段平级,不可在 http 内使用
  • 生产环境建议将 server 配置拆分到 conf.d 目录

模块化配置

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

拆分后每个 .conf 文件只包含一个 server 块。

要点总结

  • 配置文件采用 main → events/http → server → location 层级
  • main 段定义全局参数,events 段处理连接,http 段处理 HTTP 请求
  • server 段定义虚拟主机,location 段定义路径匹配规则
  • stream 和 mail 段与 http 段平级,分别用于四层代理和邮件代理
  • 生产环境建议将 server 配置拆分到 conf.d 或 sites-enabled 目录

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

← 上一篇 nginx日志配置
下一篇 → nginx配置语法规则
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

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

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