Skip to content

配置文件结构

Nginx配置文件采用层次化的块结构,理解这种结构对于正确配置Nginx非常重要。

配置文件层次结构

Nginx配置文件由多个嵌套的块组成,从外到内依次为:

Main (全局块)
├── Events (事件块)
└── HTTP (HTTP块)
    ├── Server (服务器块)
    │   └── Location (位置块)
    ├── Upstream (上游块)
    └── 其他HTTP模块块

全局块

全局块包含影响Nginx全局运行的配置指令。

位置

nginx
user  nginx;
worker_processes  auto;
error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;

常用指令

指令说明示例
user运行用户user nginx;
worker_processesWorker进程数worker_processes auto;
error_log错误日志error_log /var/log/nginx/error.log;
pidPID文件路径pid /var/run/nginx.pid;
worker_rlimit_nofile文件描述符限制worker_rlimit_nofile 65535;

Events块

Events块配置影响Nginx处理连接的方式。

位置

nginx
events {
    worker_connections  1024;
    use epoll;
}

常用指令

指令说明示例
worker_connections每个Worker的最大连接数worker_connections 1024;
use事件处理模型use epoll;
multi_accept同时接受所有连接multi_accept on;
accept_mutex连接互斥锁accept_mutex off;

HTTP块

HTTP块是Nginx最核心的块,包含HTTP服务的所有配置。

位置

nginx
http {
    include       /etc/nginx/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;

    server {
        listen       80;
        server_name  localhost;

        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
        }
    }
}

常用指令

指令说明示例
include包含其他配置文件include /etc/nginx/mime.types;
default_type默认MIME类型default_type application/octet-stream;
sendfile启用高效文件传输sendfile on;
keepalive_timeout长连接超时keepalive_timeout 65;
client_max_body_size请求体最大大小client_max_body_size 20m;

Server块

Server块配置虚拟主机,可以定义多个Server块。

位置

nginx
server {
    listen       80;
    server_name  example.com www.example.com;

    location / {
        root   /var/www/html;
        index  index.html index.htm;
    }

    location /api {
        proxy_pass http://backend;
    }
}

常用指令

指令说明示例
listen监听端口listen 80;
server_name服务器名称server_name example.com;
root网站根目录root /var/www/html;
index默认首页index index.html;
access_log访问日志access_log /var/log/nginx/access.log;
error_log错误日志error_log /var/log/nginx/error.log;

Location块

Location块配置URL匹配规则和处理方式。

位置

nginx
location / {
    root   /var/www/html;
    index  index.html;
}

location ~ \.php$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

匹配规则

规则说明示例
=精确匹配location = /
^~前缀匹配,停止正则搜索location ^~ /images/
~正则匹配(区分大小写)location ~ \.php$
~*正则匹配(不区分大小写)location ~* \.(jpg|jpeg|png)$
无修饰符前缀匹配location /

匹配优先级

  1. = 精确匹配
  2. ^~ 前缀匹配
  3. ~~* 正则匹配(按配置顺序)
  4. 前缀匹配(最长匹配)

Upstream块

Upstream块定义后端服务器组,用于负载均衡。

位置

nginx
upstream backend {
    server 192.168.1.10:8080;
    server 192.168.1.11:8080;
    server 192.168.1.12:8080;
}

server {
    location / {
        proxy_pass http://backend;
    }
}

常用指令

指令说明示例
server后端服务器server 192.168.1.10:8080;
weight权重server 192.168.1.10:8080 weight=2;
max_fails最大失败次数server 192.168.1.10:8080 max_fails=3;
fail_timeout失败超时时间server 192.168.1.10:8080 fail_timeout=30s;
backup备用服务器server 192.168.1.10:8080 backup;

配置指令分类

简单指令

由指令名和参数组成,以分号结尾:

nginx
worker_processes auto;

块指令

由指令名、参数和花括号组成:

nginx
events {
    worker_connections 1024;
}

配置文件组织

主配置文件

/etc/nginx/nginx.conf:主配置文件

额外配置文件

nginx
# 包含所有conf.d目录下的配置文件
include /etc/nginx/conf.d/*.conf;

# 包含所有启用的站点配置
include /etc/nginx/sites-enabled/*;

推荐结构

/etc/nginx/
├── nginx.conf              # 主配置文件
├── conf.d/                 # 额外配置目录
│   ├── gzip.conf          # Gzip配置
│   └── security.conf      # 安全配置
├── sites-available/        # 可用站点配置
│   ├── example.com.conf   # 站点1配置
│   └── test.com.conf      # 站点2配置
└── sites-enabled/          # 启用站点配置
    ├── example.com.conf   # 启用的站点1
    └── test.com.conf      # 启用的站点2

配置继承

继承规则

子块会继承父块的配置,但子块的配置会覆盖父块的配置。

示例

nginx
http {
    keepalive_timeout 65;

    server {
        # 继承http块的keepalive_timeout 65

        location / {
            # 继承server块的keepalive_timeout 65
        }

        location /api {
            keepalive_timeout 120;  # 覆盖父块配置
        }
    }
}

配置变量

内置变量

Nginx提供丰富的内置变量,可以在配置中使用。

nginx
$remote_addr          # 客户端IP
$remote_user          # 认证用户名
$time_local           # 本地时间
$request              # 请求行
$status               # 状态码
$body_bytes_sent      # 发送字节数
$http_referer         # 来源页面
$http_user_agent      # 用户代理
$server_name          # 服务器名称
$request_uri          # 请求URI
$document_root        # 文档根目录
$fastcgi_script_name  # FastCGI脚本名

自定义变量

nginx
set $my_var "hello world";

配置最佳实践

1. 模块化配置

将配置拆分为多个文件,便于管理:

nginx
# 主配置文件
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;

2. 注释说明

为复杂配置添加注释:

nginx
# 启用Gzip压缩
gzip on;

3. 测试配置

修改配置后先测试:

bash
nginx -t

4. 平滑重载

使用重载而非重启:

bash
nginx -s reload

总结

Nginx配置文件结构的关键点:

  • 层次化:全局 → Events → HTTP → Server → Location
  • 继承性:子块继承父块配置
  • 模块化:可以拆分为多个配置文件
  • 灵活性:支持变量和条件判断

理解配置文件结构,是掌握Nginx配置的基础。