Nginx 配置文件结构

理解 Nginx 配置文件的结构是掌握 Nginx 的关键。本章节将详细介绍配置文件的各个部分。

配置文件位置

默认位置

操作系统主配置文件额外配置目录
Linux/etc/nginx/nginx.conf/etc/nginx/conf.d/
macOS/usr/local/etc/nginx/nginx.conf/usr/local/etc/nginx/servers/
Windowsconf/nginx.confconf/conf.d/

查看配置文件

# Linux/macOS
cat /etc/nginx/nginx.conf

# Windows
type conf\nginx.conf

配置文件结构

基本结构

# 全局配置
user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;

# 事件配置
events {
    worker_connections  1024;
}

# HTTP 配置
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;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }
    }

    # 包含额外配置
    include /etc/nginx/conf.d/*.conf;
}

配置块说明

Main 块(全局配置)

user  nginx;                    # 运行 Nginx 的用户
worker_processes  auto;         # 工作进程数
error_log  /var/log/nginx/error.log notice;  # 错误日志
pid        /var/run/nginx.pid;  # PID 文件位置

Events 块(事件处理)

events {
    worker_connections  1024;   # 每个工作进程的最大连接数
}

HTTP 块(HTTP 服务器配置)

http {
    include       /etc/nginx/mime.types;           # MIME 类型
    default_type  application/octet-stream;        # 默认 MIME 类型

    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
    keepalive_timeout  65;                          # 保持连接超时

    # 服务器配置
    server {
        listen       80;
        server_name  localhost;

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

    # 包含额外配置
    include /etc/nginx/conf.d/*.conf;
}

Server 块(虚拟主机配置)

server {
    listen       80;                          # 监听端口
    server_name  localhost;                   # 服务器名称

    location / {
        root   /usr/share/nginx/html;        # 网站根目录
        index  index.html index.htm;          # 默认首页
    }

    error_page   500 502 503 504  /50x.html;  # 错误页面
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

Location 块(URL 匹配配置)

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

location /images/ {
    root   /usr/share/nginx;
}

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;
}

常用指令

全局指令

指令说明示例
user运行 Nginx 的用户user nginx;
worker_processes工作进程数worker_processes auto;
error_log错误日志error_log /var/log/nginx/error.log;
pidPID 文件pid /var/run/nginx.pid;

Events 指令

指令说明示例
worker_connections最大连接数worker_connections 1024;
use事件模型use epoll;

HTTP 指令

指令说明示例
include包含文件include mime.types;
default_type默认 MIME 类型default_type application/octet-stream;
log_format日志格式log_format main ...;
access_log访问日志access_log /var/log/nginx/access.log;
sendfile启用 sendfilesendfile on;
keepalive_timeout保持连接超时keepalive_timeout 65;
gzip启用 gzipgzip on;

Server 指令

指令说明示例
listen监听端口listen 80;
server_name服务器名称server_name example.com;
root网站根目录root /var/www/html;
index默认首页index index.html;
error_page错误页面error_page 404 /404.html;

Location 指令

指令说明示例
root根目录root /var/www/html;
alias别名alias /var/www/images;
proxy_pass代理地址proxy_pass http://backend;
try_files尝试文件try_files $uri $uri/ =404;
return返回响应return 200 "OK";

Location 匹配规则

匹配优先级

  1. = 精确匹配
  2. ^~ 前缀匹配(不检查正则)
  3. ~~* 正则匹配
  4. 前缀匹配

匹配示例

location = / {                    # 精确匹配 /
    [ configuration A ]
}

location / {                      # 通用匹配
    [ configuration B ]
}

location /documents/ {            # 前缀匹配 /documents/
    [ configuration C ]
}

location ^~ /images/ {            # 前缀匹配 /images/(不检查正则)
    [ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {   # 正则匹配(不区分大小写)
    [ configuration E ]
}

匹配示例说明

请求匹配配置
/A
/index.htmlB
/documents/document.htmlC
/images/1.gifD
/documents/1.jpgE

变量

常用变量

变量说明
$host请求的主机名
$remote_addr客户端 IP 地址
$remote_user客户端用户名
$request完整的请求行
$status响应状态码
$body_bytes_sent发送的字节数
$http_referer请求来源
$http_user_agent客户端浏览器信息
$http_x_forwarded_for客户端真实 IP(代理)
$request_uri完整的请求 URI
$document_root当前请求的文档根目录
$fastcgi_script_nameFastCGI 脚本名称

使用变量

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

add_header X-Request-ID $request_id;

注释

# 这是一个注释
user  nginx;
worker_processes  auto;  # 自动检测 CPU 核心数

包含文件

# 包含 MIME 类型
include /etc/nginx/mime.types;

# 包含额外配置
include /etc/nginx/conf.d/*.conf;

# 包含 FastCGI 参数
include fastcgi_params;

配置测试

# 测试配置
nginx -t

# 显示配置
nginx -T

最佳实践

1. 使用 include 组织配置

# 主配置文件
http {
    include /etc/nginx/mime.types;
    include /etc/nginx/conf.d/*.conf;
}

# 网站配置文件
# /etc/nginx/conf.d/example.com.conf
server {
    listen 80;
    server_name example.com;
    # ...
}

2. 使用变量提高灵活性

server {
    listen 80;
    server_name $host;
    root /var/www/$host;
}

3. 使用精确匹配提高性能

location = /favicon.ico {
    log_not_found off;
    access_log off;
}

4. 合理使用 location 匹配

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

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

配置示例

完整示例

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

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;

    # Gzip 压缩
    gzip  on;
    gzip_disable "msie6";

    # 虚拟主机
    server {
        listen       80;
        server_name  localhost;

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

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }
    }

    # 包含额外配置
    include /etc/nginx/conf.d/*.conf;
}