<返回目录     Powered by claud/xia兄

第2课: Nginx配置文件结构

nginx.conf、配置块、指令语法

配置文件概述

Nginx的配置文件采用简洁的文本格式,由指令(directives)和指令块(blocks)组成。主配置文件通常位于 /etc/nginx/nginx.conf/usr/local/nginx/conf/nginx.conf

配置文件语法规则

Nginx配置文件遵循特定的语法规则:

常见语法错误:
  • 忘记分号 ;
  • 花括号不匹配 {}
  • 指令拼写错误
  • 参数格式错误

常用配置指令详解

全局块常用指令

指令 说明 示例
user 指定运行Nginx的用户和组 user nginx nginx;
worker_processes 工作进程数,auto表示自动检测CPU核心数 worker_processes auto;
error_log 错误日志路径和级别(debug, info, notice, warn, error, crit) error_log /var/log/nginx/error.log warn;
pid PID文件路径 pid /var/run/nginx.pid;

events块常用指令

指令 说明 示例
worker_connections 每个工作进程的最大连接数 worker_connections 1024;
use 指定事件模型(epoll, kqueue, select等) use epoll;
multi_accept 是否允许同时接受多个连接 multi_accept on;

server块常用指令

指令 说明 示例
listen 监听端口,可指定IP地址 listen 80;listen 192.168.1.100:80;
server_name 服务器名称,支持通配符和正则表达式 server_name example.com *.example.com;
root 网站根目录 root /var/www/html;
index 默认首页文件 index index.html index.htm index.php;

location块匹配规则

location块支持多种匹配方式:

location块常用指令

指令 说明 示例
root 指定location的根目录 root /var/www/html;
alias 路径别名,location路径会被替换 alias /var/www/images/;
proxy_pass 反向代理到后端服务器 proxy_pass http://backend;
try_files 文件查找规则 try_files $uri $uri/ =404;
配置文件特点:
  • 语法简单,易于理解
  • 支持include指令引入其他配置文件
  • 支持变量和条件判断
  • 配置修改后需要重载才能生效

配置文件的层级结构

Nginx配置文件采用树状层级结构,主要包含以下几个层级:

配置文件结构示意图

nginx.conf
├── 全局块 (main context)
├── events块 (events context)
└── http块 (http context)
    ├── server块 (server context)
    │   ├── location块 (location context)
    │   └── location块
    └── server块
        └── location块

基本配置文件结构

# ======================
# 全局块 (main context)
# ======================
user nginx;                        # 运行Nginx的用户
worker_processes auto;             # 工作进程数,auto表示自动检测CPU核心数
error_log /var/log/nginx/error.log warn;  # 错误日志路径和级别
pid /var/run/nginx.pid;            # PID文件路径

# ======================
# events块 (events context)
# ======================
events {
    worker_connections 1024;       # 每个工作进程的最大连接数
    use epoll;                     # 使用epoll事件模型(Linux)
    multi_accept on;               # 允许一个工作进程同时接受多个连接
}

# ======================
# http块 (http context)
# ======================
http {
    # 包含MIME类型定义
    include /etc/nginx/mime.types;
    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;  # 访问日志

    # ======================
    # server块 (server context)
    # ======================
    server {
        listen 80;                 # 监听80端口
        server_name example.com www.example.com;  # 服务器名称

        # ======================
        # location块 (location context)
        # ======================
        location / {
            root /usr/share/nginx/html;  # 网站根目录
            index index.html index.htm;  # 默认首页文件
            try_files $uri $uri/ =404;   # 文件查找规则
        }

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

全局块配置详解

全局块配置影响整个Nginx服务器的运行。

示例1:基础全局配置

# 运行Nginx的用户和组
user nginx nginx;

# worker进程数,建议设置为CPU核心数
worker_processes 4;

# 错误日志路径和级别(debug|info|notice|warn|error|crit)
error_log /var/log/nginx/error.log error;

# 进程PID文件路径
pid /var/run/nginx.pid;

示例2:高级全局配置

# 自动检测CPU核心数
worker_processes auto;

# 绑定worker进程到特定CPU核心(提升性能)
worker_cpu_affinity auto;

# 单个worker进程可以打开的最大文件描述符数量
worker_rlimit_nofile 65535;

# 优先级设置(-20到19,数值越小优先级越高)
worker_priority -10;

events块配置详解

events块配置影响Nginx服务器与客户端的网络连接。

示例3:基础events配置

events {
    # 单个worker进程的最大并发连接数
    worker_connections 1024;

    # 使用epoll事件驱动模型(Linux推荐)
    use epoll;

    # 尽可能多地接受连接
    multi_accept on;
}

示例4:高并发events配置

events {
    # 高并发场景下的连接数
    worker_connections 10240;

    # Linux下使用epoll,FreeBSD使用kqueue
    use epoll;

    # 允许同时接受多个新连接
    multi_accept on;

    # 接受连接的互斥锁(off可提高性能但可能导致惊群)
    accept_mutex off;
}

http块配置详解

http块是配置的核心部分,包含了大部分HTTP服务器的配置。

示例5:基础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"';

    # 访问日志路径
    access_log /var/log/nginx/access.log main;

    # 开启高效文件传输模式
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    # 连接超时时间
    keepalive_timeout 65;

    # 引入其他配置文件
    include /etc/nginx/conf.d/*.conf;
}

示例6:优化的http配置

http {
    include mime.types;
    default_type application/octet-stream;

    # 字符集
    charset utf-8;

    # 隐藏Nginx版本号(安全)
    server_tokens off;

    # 客户端请求体大小限制
    client_max_body_size 100m;
    client_body_buffer_size 128k;

    # 超时设置
    client_header_timeout 30s;
    client_body_timeout 30s;
    send_timeout 30s;
    keepalive_timeout 65s;

    # 文件传输优化
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    # 开启gzip压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1k;
    gzip_comp_level 6;
    gzip_types text/plain text/css application/json application/javascript;
}

server块配置详解

server块定义虚拟主机,一个http块可以包含多个server块。

示例7:基础server配置

server {
    # 监听端口
    listen 80;

    # 服务器域名
    server_name www.example.com example.com;

    # 网站根目录
    root /var/www/html;

    # 默认首页文件
    index index.html index.htm;

    # 访问日志
    access_log /var/log/nginx/example.access.log;
    error_log /var/log/nginx/example.error.log;

    # 根路径location
    location / {
        try_files $uri $uri/ =404;
    }
}

示例8:多域名server配置

# 主站配置
server {
    listen 80;
    server_name www.example.com example.com;
    root /var/www/example;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }
}

# 子域名配置
server {
    listen 80;
    server_name blog.example.com;
    root /var/www/blog;
    index index.php index.html;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

# 默认server(处理未匹配的请求)
server {
    listen 80 default_server;
    server_name _;
    return 444;  # 关闭连接
}

location块配置详解

location块用于匹配URI并定义请求的处理方式。

示例9:location匹配规则

server {
    listen 80;
    server_name example.com;

    # 精确匹配
    location = / {
        return 200 "精确匹配根路径";
    }

    # 前缀匹配
    location /images/ {
        root /var/www;
        # 实际路径:/var/www/images/
    }

    # 正则匹配(区分大小写)
    location ~ \.(jpg|png|gif)$ {
        root /var/www/images;
        expires 30d;
    }

    # 正则匹配(不区分大小写)
    location ~* \.(JPG|PNG|GIF)$ {
        root /var/www/images;
    }

    # 优先前缀匹配
    location ^~ /static/ {
        root /var/www;
    }

    # 通用匹配
    location / {
        proxy_pass http://backend;
    }
}

示例10:location实用配置

server {
    listen 80;
    server_name example.com;
    root /var/www/html;

    # API代理
    location /api/ {
        proxy_pass http://127.0.0.1:8000/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    # 静态文件缓存
    location ~* \.(css|js|jpg|png|gif|ico)$ {
        expires 7d;
        add_header Cache-Control "public, immutable";
    }

    # 禁止访问隐藏文件
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }

    # 防止访问备份文件
    location ~* \.(bak|backup|sql|old)$ {
        deny all;
    }
}
配置文件最佳实践:
  • 使用注释说明配置的用途,便于维护
  • 将不同站点的配置分离到独立文件中
  • 使用 include 指令组织配置文件
  • 修改配置后务必使用 nginx -t 测试
  • 使用 nginx -s reload 平滑重载配置
  • 定期备份配置文件
常见配置错误:
  • 指令末尾忘记添加分号(;)
  • 花括号不匹配
  • 路径配置错误(注意root和alias的区别)
  • 正则表达式语法错误
  • 指令放置在错误的配置块中

配置文件组织结构

推荐的配置文件组织方式:

/etc/nginx/
├── nginx.conf              # 主配置文件
├── mime.types              # MIME类型定义
├── conf.d/                 # 站点配置目录
│   ├── default.conf        # 默认站点
│   ├── example.com.conf    # 示例站点
│   └── api.conf            # API配置
├── snippets/               # 可复用配置片段
│   ├── ssl-params.conf     # SSL参数
│   ├── proxy-params.conf   # 代理参数
│   └── security.conf       # 安全配置
└── sites-available/        # 可用站点配置
    └── sites-enabled/      # 启用站点配置(软链接)

实际配置示例

示例1:静态网站配置

server {
    listen 80;
    server_name mysite.com www.mysite.com;
    
    # 网站根目录
    root /var/www/mysite;
    index index.html index.htm;
    
    # 静态资源缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
    
    # 错误页面
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

示例2:PHP应用配置

server {
    listen 80;
    server_name myapp.com;
    
    root /var/www/myapp/public;
    index index.php index.html;
    
    # PHP处理
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
    
    # 禁止访问敏感文件
    location ~ /\. {
        deny all;
    }
    
    location ~ /\.ht {
        deny all;
    }
}

示例3:反向代理配置

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

server {
    listen 80;
    server_name api.example.com;
    
    location / {
        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;
    }
}

配置文件管理最佳实践

为了便于管理和维护Nginx配置文件,建议遵循以下最佳实践:

配置文件验证和调试

在修改配置文件后,务必使用以下命令验证配置的正确性:

# 测试配置文件语法
nginx -t

# 如果配置正确,会显示以下信息
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

# 重新加载配置(不停止服务)
nginx -s reload

# 查看详细的配置信息
nginx -T

# 查看编译参数和模块
nginx -V
调试技巧:
  • 使用 nginx -t 测试语法,避免配置错误导致服务中断
  • 修改配置后,先测试再重载,确保服务稳定
  • 查看错误日志 /var/log/nginx/error.log 排查问题
  • 使用 tail -f /var/log/nginx/error.log 实时监控错误

本课总结

通过本课的学习,你应该已经掌握了:

课后作业

任务1:查看现有Nginx配置文件,理解各个配置块的作用

任务2:创建一个简单的虚拟主机配置,配置静态网站

任务3:使用nginx -t命令测试配置文件的语法正确性

任务4:尝试修改配置并重载,观察服务变化

知识扩展

配置优化建议:

  • 根据服务器硬件调整worker_processes和worker_connections
  • 启用gzip压缩减少传输数据量
  • 配置合理的缓存策略提升性能
  • 使用HTTP/2协议提升加载速度
  • 配置安全头增强安全性

实践练习

练习任务:
  1. 查看并分析你的nginx.conf文件结构
  2. 创建一个新的server块配置文件在conf.d目录下
  3. 配置一个监听8080端口的虚拟主机
  4. 添加多个location块处理不同的URI路径
  5. 使用 nginx -t 测试配置文件语法
  6. 使用 nginx -s reload 重载配置并访问测试
  7. 尝试配置一个默认server处理未匹配的域名请求
  8. 创建一个snippets目录并将通用配置提取为可复用片段

总结

本课学习了Nginx配置文件的完整结构,包括全局块、events块、http块、server块和location块的配置方法。理解配置文件的层级关系和指令作用域是掌握Nginx的基础。通过合理组织配置文件,可以提高配置的可维护性和可读性。