Nginx 配置文件结构

Nginx 配置文件的组织结构和语法规则


📋 目录


配置文件位置

默认配置文件路径

Linux:
├── /etc/nginx/nginx.conf              # 主配置文件
├── /etc/nginx/mime.types              # MIME 类型定义
├── /etc/nginx/fastcgi_params          # FastCGI 参数
├── /etc/nginx/uwsgi_params            # uWSGI 参数
├── /etc/nginx/scgi_params             # SCGI 参数
├── /etc/nginx/conf.d/                 # 通用配置片段
├── /etc/nginx/sites-available/        # 可用站点(Ubuntu/Debian)
└── /etc/nginx/sites-enabled/          # 启用站点(Ubuntu/Debian)

Windows:
└── C:\nginx\conf\nginx.conf           # 主配置文件

查找配置文件

# 查看 Nginx 使用的配置文件
nginx -t
 
# 输出示例:
# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful
 
# 查看所有配置(包括 include)
nginx -T

配置文件语法

基本语法规则

# 1. 指令以分号结尾
directive value1 value2 ...;
 
# 2. 块指令使用大括号
directive {
    sub_directive value;
}
 
# 3. 注释使用 #
# 这是注释
 
# 4. 支持续行符
access_log /var/log/nginx/access.log  \
           main;
 
# 5. 路径可以使用绝对路径或相对路径
include /etc/nginx/conf.d/*.conf;      # 绝对路径
include conf.d/*.conf;                 # 相对路径(相对于 nginx.conf 所在目录)

指令格式

# 简单指令
directive value;
 
# 带参数的指令
directive param1=value1 param2=value2;
 
# 块指令
directive {
    sub_directive1 value1;
    sub_directive2 value2;
}
 
# 多个值
directive value1 value2 value3;
 
# 数组形式
directive value1,
        value2,
        value3;

变量使用

# 内置变量
$remote_addr      # 客户端 IP
$remote_user      # 客户端用户
$time_local       # 本地时间
$request          # 完整请求
$status           # 响应状态码
$body_bytes_sent  # 响应体大小
$http_referer     # 来源页面
$http_user_agent  # 用户代理
 
# 自定义变量
set $my_var "hello";
set $full_path "/data$uri";
 
# 变量使用
return 200 "IP: $remote_addr\n";

配置上下文

配置层级结构

# 全局上下文(Main Context)
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
 
# Events 上下文
events {
    worker_connections 1024;
    use epoll;
}
 
# HTTP 上下文
http {
    include mime.types;
    default_type application/octet-stream;
 
    # Upstream 上下文(在 http 中)
    upstream backend {
        server 127.0.0.1:8080;
        server 127.0.0.1:8081;
    }
 
    # Server 上下文(在 http 中)
    server {
        listen 80;
        server_name example.com;
 
        # Location 上下文(在 server 中)
        location / {
            root /var/www/html;
            index index.html;
        }
 
        # Location 上下文
        location /api/ {
            proxy_pass http://backend;
        }
    }
 
    # 另一个 Server 上下文
    server {
        listen 443 ssl;
        server_name secure.example.com;
 
        location / {
            root /var/www/secure;
        }
    }
}
 
# Mail 上下文(可选)
mail {
    # ...
}
 
# Stream 上下文(可选)
stream {
    # ...
}

Main 上下文

# 全局配置,影响整个 Nginx
user nginx;                    # 运行用户
group nginx;                   # 运行组
worker_processes auto;         # worker 进程数
error_log /var/log/nginx/error.log warn;  # 错误日志
pid /var/run/nginx.pid;        # PID 文件
daemon on;                     # 是否以守护进程运行
worker_rlimit_nofile 65535;    # worker 打开文件数限制
include /etc/nginx/modules-enabled/*.conf;  # 加载模块

Events 上下文

events {
    worker_connections 1024;           # 每个 worker 的连接数
    use epoll;                         # 使用 epoll(Linux)
    multi_accept on;                   # 批量接受连接
    accept_mutex on;                   # 串行接受连接
    accept_mutex_delay 500ms;          # 串行延迟
}

Http 上下文

http {
    include mime.types;                # MIME 类型
    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;                       # 开启 sendfile
    tcp_nopush on;                     # 优化包发送
    tcp_nodelay on;                    # 禁用 Nagle
 
    # 连接保持
    keepalive_timeout 65;              # 长连接超时
    keepalive_requests 100;            # 长连接最大请求数
 
    # 压缩
    gzip on;                           # 开启 Gzip
    gzip_types text/plain text/css;    # 压缩类型
 
    # 客户端限制
    client_max_body_size 1m;           # 请求体大小限制
    client_header_buffer_size 1k;      # 请求头缓冲区
 
    # Include 其他配置
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

Server 上下文

server {
    listen 80;                         # 监听端口
    listen [::]:80 ipv6only=on;        # IPv6
 
    server_name example.com www.example.com;  # 域名
 
    # 访问日志
    access_log /var/log/nginx/example.access.log main;
 
    # 错误日志
    error_log /var/log/nginx/example.error.log warn;
 
    # 错误页面
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
 
    # 根目录
    root /var/www/example;
 
    # 默认首页
    index index.html index.htm;
 
    # Location 配置
    location / {
        try_files $uri $uri/ =404;
    }
 
    # 其他 location
    location /api/ {
        proxy_pass http://backend;
    }
}

Location 上下文

location [modifier] pattern {
    # 配置指令
}
 
# 匹配方式
location = / {                      # 精确匹配
    # ...
}
 
location / {                        # 前缀匹配(最低优先级)
    # ...
}
 
location /api/ {                    # 前缀匹配
    # ...
}
 
location ~ \.php$ {                 # 正则匹配(区分大小写)
    # ...
}
 
location ~* \.(jpg|jpeg|png)$ {    # 正则匹配(不区分大小写)
    # ...
}
 
location ^~ /static/ {              # 优先前缀匹配
    # ...
}

Upstream 上下文

upstream backend {
    server backend1.example.com:8080 weight=5;
    server backend2.example.com:8080 weight=3;
    server backend3.example.com:8080 backup;
 
    keepalive 32;                    # 长连接数
    keepalive_timeout 60s;           # 长连接超时
    keepalive_requests 100;          # 长连接最大请求数
 
    ip_hash;                         # IP 哈希
    least_conn;                      # 最少连接
}
 
# 使用 upstream
server {
    location / {
        proxy_pass http://backend;
    }
}

指令类型

核心指令

# 全局指令(只能在 main 上下文)
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
 
# Events 指令(只能在 events 上下文)
events {
    worker_connections 1024;
    use epoll;
}
 
# HTTP 指令(只能在 http 上下文)
http {
    include mime.types;
    default_type application/octet-stream;
}

标准模块指令

# HTTP 核心模块
server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    index index.html;
}
 
location / {
    try_files $uri $uri/ =404;
}
 
# 访问控制模块
location /admin/ {
    allow 192.168.1.0/24;
    deny all;
}
 
# Gzip 模块
gzip on;
gzip_types text/plain text/css;
 
# SSL 模块
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;

第三方模块指令

# 如果编译了第三方模块
load_module modules/ngx_http_geoip_module.so;
 
http {
    geoip_country /usr/share/GeoIP/GeoIP.dat;
 
    map $geoip_country_code $allowed_country {
        default no;
        CN yes;
        US yes;
    }
 
    server {
        if ($allowed_country = no) {
            return 403;
        }
    }
}

Include 机制

Include 语法

# 包含单个文件
include /etc/nginx/mime.types;
 
# 包含目录下所有 .conf 文件
include /etc/nginx/conf.d/*.conf;
 
# 包含多个目录
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
 
# 相对路径(相对于 nginx.conf 所在目录)
include conf.d/*.conf;

使用场景

# 1. 分离 MIME 类型
include mime.types;
 
# 2. 分离虚拟主机配置
include /etc/nginx/sites-enabled/*;
 
# 3. 分离公共配置片段
http {
    include /etc/nginx/conf.d/logging.conf;
    include /etc/nginx/conf.d/gzip.conf;
    include /etc/nginx/conf.d/proxy.conf;
}
 
# 4. 条件包含
# 注意: Nginx 不支持条件 include,但可以通过变量实现
map $hostname $config {
    default "default.conf";
    hostnames;
    example.com "example.conf";
}
 
include /etc/nginx/custom/$config;

最佳实践

# /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
 
events {
    worker_connections 1024;
}
 
http {
    include mime.types;
    default_type application/octet-stream;
 
    # 基础配置
    include /etc/nginx/conf.d/basic.conf;
 
    # 日志配置
    include /etc/nginx/conf.d/logging.conf;
 
    # 性能优化
    include /etc/nginx/conf.d/performance.conf;
 
    # 安全配置
    include /etc/nginx/conf.d/security.conf;
 
    # 虚拟主机
    include /etc/nginx/sites-enabled/*;
}

配置示例

完整配置示例

# /etc/nginx/nginx.conf
 
# Main 上下文
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
 
# Events 上下文
events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}
 
# HTTP 上下文
http {
    # MIME 类型
    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"';
 
    log_format json '{"time":"$time_iso8601","remote_addr":"$remote_addr",'
                    '"request":"$request","status":$status,"bytes_sent":$bytes_sent}';
 
    # 访问日志
    access_log /var/log/nginx/access.log main;
 
    # 错误日志(已在 main 中定义)
    # error_log /var/log/nginx/error.log warn;
 
    # 文件传输优化
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
 
    # 连接保持
    keepalive_timeout 65;
    keepalive_requests 100;
 
    # 客户端限制
    client_max_body_size 1m;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 8k;
 
    # Gzip 压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/json
        application/javascript
        application/xml+rss
        application/atom+xml
        image/svg+xml;
 
    # 虚拟主机
    server {
        listen 80;
        server_name localhost;
 
        access_log /var/log/nginx/localhost.access.log main;
        error_log /var/log/nginx/localhost.error.log warn;
 
        root /usr/share/nginx/html;
        index index.html index.htm;
 
        location / {
            try_files $uri $uri/ =404;
        }
 
        error_page 404 /404.html;
        error_page 500 502 503 504 /50x.html;
 
        location = /50x.html {
            root /usr/share/nginx/html;
        }
    }
 
    # 包含其他配置
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

虚拟主机配置示例

# /etc/nginx/sites-available/example.com
server {
    listen 80;
    listen [::]:80 ipv6only=on;
 
    server_name example.com www.example.com;
 
    root /var/www/example.com;
    index index.html index.htm index.php;
 
    # 访问日志
    access_log /var/log/nginx/example.com.access.log main;
    error_log /var/log/nginx/example.com.error.log warn;
 
    # 错误页面
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
 
    # 静态文件缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
 
    # API 代理
    location /api/ {
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
 
    # PHP 处理
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
 
    # 限制访问
    location /admin/ {
        allow 192.168.1.0/24;
        deny all;
        auth_basic "Admin Area";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
 
    # 禁止访问隐藏文件
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }
}
 
# 启用站点(Ubuntu/Debian)
# sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

🔧 配置检查

验证配置

# 检查语法
sudo nginx -t
 
# 检查并显示所有配置
sudo nginx -T
 
# 检查指定配置文件
sudo nginx -t -c /path/to/custom/nginx.conf

常见错误

# 错误: 缺少分号
# location / {
#     root /var/www/html    # 错误: 缺少分号
# }
 
# 正确:
location / {
    root /var/www/html;
}
 
# 错误: 括号不匹配
# server {
#     listen 80;
#     location / {
#         root /var/www/html;
#     }
# # 错误: 缺少 server 的关闭括号
 
# 正确:
server {
    listen 80;
    location / {
        root /var/www/html;
    }
}
 
# 错误: 指令位置错误
# http {
#     worker_connections 1024;  # 错误: 不能在 http 上下文中
# }
 
# 正确:
events {
    worker_connections 1024;
}

📚 相关链接


标签: nginx 配置 结构 语法 管理