前言:为什么选择 Nginx

Nginx(读作 Engine-X)是全球约34%的网站所使用的Web服务器,与 Apache 并称为两大主流。2004年,俄罗斯开发者 Igor Sysoev 为解决 C10K 问题(同时处理1万个并发连接)而设计了 Nginx,它采用事件驱动(event-driven)异步架构,以较少的内存即可处理大量并发连接。

在实际工作中,Nginx 不仅仅是一个简单的Web服务器,还承担着反向代理负载均衡器API Gateway缓存服务器等多种角色。尤其随着容器环境和微服务架构的普及,Nginx 的重要性愈发凸显。

本指南将系统地介绍从 Nginx 的安装到实战运维所需的所有配置。从初学者也能跟着操作的基础配置,到实际工作中必须掌握的高级配置,都将结合实际配置文件示例进行详细说明。

1. Nginx 安装

1.1 Ubuntu/Debian 系列安装

# 更新软件包列表后安装
sudo apt update
sudo apt install nginx -y

# 确认版本
nginx -v

# 启动服务并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx

# 查看状态
sudo systemctl status nginx

1.2 RHEL/CentOS/Rocky Linux 系列安装

# 添加 EPEL 仓库(CentOS 7)
sudo yum install epel-release -y
sudo yum install nginx -y

# Rocky Linux 9 / RHEL 9
sudo dnf install nginx -y

# 启动服务并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx

# 防火墙放行
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

1.3 从官方 Nginx 仓库安装最新版本

发行版默认仓库中的 Nginx 版本往往较旧。如果需要最新功能,可以添加官方仓库:

# Ubuntu - 添加 Nginx 官方仓库
sudo apt install curl gnupg2 ca-certificates lsb-release -y

# 添加签名密钥
curl -fsSL https://nginx.org/keys/nginx_signing.key | sudo gpg --dearmor -o /usr/share/keyrings/nginx-archive-keyring.gpg

# 添加仓库(stable)
echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] http://nginx.org/packages/ubuntu $(lsb_release -cs) nginx" | sudo tee /etc/apt/sources.list.d/nginx.list

# 安装
sudo apt update
sudo apt install nginx -y
TIP: 官方仓库的 Nginx 有 mainline(最新功能,奇数版本号)和 stable(稳定版,偶数版本号)两个发布通道。生产环境建议使用 stable

1.4 安装验证

# 在浏览器中确认:http://服务器IP
# 或通过命令行确认
curl -I http://localhost

# 确认安装路径
nginx -V    # 查看编译选项和模块
nginx -t    # 验证配置语法

2. Nginx 目录结构与配置文件

2.1 核心目录结构

路径 说明
/etc/nginx/ 主配置目录
/etc/nginx/nginx.conf 主配置文件(所有配置的起点)
/etc/nginx/conf.d/ 附加配置文件(*.conf 自动加载)
/etc/nginx/sites-available/ 可用站点配置(Ubuntu)
/etc/nginx/sites-enabled/ 已启用站点的符号链接(Ubuntu)
/etc/nginx/mime.types MIME 类型映射
/var/log/nginx/access.log 访问日志
/var/log/nginx/error.log 错误日志
/var/www/html/ 默认Web根目录
/usr/share/nginx/html/ 默认Web根目录(RHEL 系列)

2.2 nginx.conf 基本结构

Nginx 配置采用块(block)结构,以层级方式嵌套:

# === 全局上下文(Main Context)===
user nginx;                          # Worker 进程运行用户
worker_processes auto;               # Worker 进程数(auto = CPU 核心数)
error_log /var/log/nginx/error.log warn;  # 错误日志路径及级别
pid /run/nginx.pid;                  # PID 文件路径

# === 事件上下文 ===
events {
    worker_connections 1024;         # 每个 Worker 的最大并发连接数
    use epoll;                       # 事件处理方式(Linux)
    multi_accept on;                 # 一次接受多个连接
}

# === 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"';

    access_log /var/log/nginx/access.log main;

    sendfile on;                     # 内核级文件传输
    tcp_nopush on;                   # 配合 sendfile 使用
    tcp_nodelay on;                  # 防止小数据包延迟
    keepalive_timeout 65;            # 连接保持时间

    # gzip 压缩
    gzip on;
    gzip_types text/plain text/css application/json application/javascript;

    # 加载附加配置文件
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;  # Ubuntu 方式
}
注意: 修改配置后,务必使用 nginx -t 验证语法,然后使用 sudo systemctl reload nginx 应用更改。使用 reload 代替 restart 可以在不中断服务的情况下使配置生效。

3. Server Block(虚拟主机)配置

Server Block 相当于 Apache 的 VirtualHost,允许在一台 Nginx 服务器上运营多个域名(站点)

3.1 基本静态网站

# /etc/nginx/conf.d/example.com.conf
server {
    listen 80;                       # IPv4 端口
    listen [::]:80;                  # IPv6 端口
    server_name example.com www.example.com;

    root /var/www/example.com/html;  # 文档根目录
    index index.html index.htm;      # 默认索引文件

    # 默认 location
    location / {
        try_files $uri $uri/ =404;   # 文件 → 目录 → 404
    }

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

    # 日志配置(按站点分离)
    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;
}
# 创建Web根目录
sudo mkdir -p /var/www/example.com/html
sudo chown -R $USER:$USER /var/www/example.com/html

# 创建测试页面
echo "<h1>Welcome to example.com</h1>" > /var/www/example.com/html/index.html

# 验证配置并应用
sudo nginx -t
sudo systemctl reload nginx

3.2 Ubuntu 的 sites-available / sites-enabled 模式

# 创建配置文件
sudo nano /etc/nginx/sites-available/example.com

# 通过符号链接启用
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

# 禁用默认站点(如需要)
sudo rm /etc/nginx/sites-enabled/default

# 应用
sudo nginx -t
sudo systemctl reload nginx

3.3 多域名运营(多站点)

# 站点 A:/etc/nginx/conf.d/site-a.conf
server {
    listen 80;
    server_name site-a.com www.site-a.com;
    root /var/www/site-a/html;
    index index.html;

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

# 站点 B:/etc/nginx/conf.d/site-b.conf
server {
    listen 80;
    server_name site-b.com www.site-b.com;
    root /var/www/site-b/html;
    index index.html;

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

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

4. Location 块 - URL 匹配的核心

location 块是 Nginx 配置中最常用且最重要的指令。它可以根据 URL 路径执行不同的处理逻辑。

4.1 匹配方式与优先级

语法 匹配方式 优先级
= /path 精确匹配(Exact Match) 第1优先(最高)
^~ /path 前缀匹配(不进行正则搜索) 第2优先
~ /regex 正则表达式(区分大小写) 第3优先
~* /regex 正则表达式(不区分大小写) 第3优先
/path 前缀匹配(最长匹配) 第4优先(默认)

4.2 实战 Location 示例

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

    # 仅精确匹配根路径
    location = / {
        # 主页专用处理
        try_files /index.html =404;
    }

    # 以 /api/ 开头的路径 → 后端代理
    location /api/ {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    # 静态文件(图片、CSS、JS)
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2?)$ {
        expires 30d;                 # 30天缓存
        add_header Cache-Control "public, immutable";
        access_log off;              # 禁用静态文件日志
    }

    # PHP 文件处理
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    # 阻止访问隐藏文件(.htaccess、.git 等)
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }

    # 防止 favicon.ico 产生 404 日志
    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    # robots.txt
    location = /robots.txt {
        log_not_found off;
        access_log off;
    }
}
TIP: 请牢记 location 块的优先级:=(精确)→ ^~(前缀优先)→ ~/~*(正则)→ 普通前缀。如果不能准确理解,可能会出现意想不到的路由问题。

5. 反向代理配置

反向代理是 Nginx 最强大的功能之一。它将客户端的请求转发到后端服务器(Node.js、Python、Java 等)并返回响应。

5.1 基本反向代理

# Node.js 应用代理(端口 3000)
server {
    listen 80;
    server_name app.example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;

        # 必要的头部转发
        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;

        # 超时设置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;

        # 缓冲设置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
    }
}

5.2 WebSocket 代理

# 需要 WebSocket 支持的场景(聊天、实时应用)
server {
    listen 80;
    server_name ws.example.com;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_http_version 1.1;

        # WebSocket 升级头部
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;

        # WebSocket 连接保持时间
        proxy_read_timeout 86400s;   # 24小时
        proxy_send_timeout 86400s;
    }
}

5.3 按路径分发到多个后端

# 微服务路由
server {
    listen 80;
    server_name example.com;

    # 前端(React/Vue SPA)
    location / {
        root /var/www/frontend/dist;
        try_files $uri $uri/ /index.html;  # SPA 路由
    }

    # API 服务器(Node.js)
    location /api/ {
        proxy_pass http://127.0.0.1:3000/;    # 末尾的 / 很重要!
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    # 认证服务器(Python)
    location /auth/ {
        proxy_pass http://127.0.0.1:5000/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    # 文件上传服务器(独立大小限制)
    location /upload/ {
        client_max_body_size 100M;   # 上传最大 100MB
        proxy_pass http://127.0.0.1:4000/;
        proxy_set_header Host $host;
    }
}
注意: 请注意 proxy_pass URL 末尾的斜杠(/)。proxy_pass http://backend/; 会去除 location 路径后转发,而 proxy_pass http://backend;(无斜杠)则会保留 location 路径一起转发。

6. 负载均衡

将流量分散到多个后端服务器,以确保高可用性和性能。

6.1 负载均衡方式

# === Round Robin(默认)===
# 按顺序轮流分配请求
upstream backend_rr {
    server 192.168.1.10:8080;
    server 192.168.1.11:8080;
    server 192.168.1.12:8080;
}

# === Weighted Round Robin ===
# 按服务器性能分配权重
upstream backend_weighted {
    server 192.168.1.10:8080 weight=5;    # 接收5倍请求
    server 192.168.1.11:8080 weight=3;
    server 192.168.1.12:8080 weight=1;
}

# === Least Connections ===
# 分配到连接数最少的服务器
upstream backend_lc {
    least_conn;
    server 192.168.1.10:8080;
    server 192.168.1.11:8080;
    server 192.168.1.12:8080;
}

# === IP Hash ===
# 同一客户端 IP 始终分配到同一服务器(保持会话)
upstream backend_hash {
    ip_hash;
    server 192.168.1.10:8080;
    server 192.168.1.11:8080;
    server 192.168.1.12:8080;
}

# 应用负载均衡
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://backend_rr;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

6.2 健康检查与故障应对

upstream backend {
    server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
    server 192.168.1.11:8080 max_fails=3 fail_timeout=30s;
    server 192.168.1.12:8080 backup;     # 备份服务器(其他服务器全部失败时使用)
    server 192.168.1.13:8080 down;       # 手动停用

    # max_fails=3:失败3次后将该服务器标记为不可用
    # fail_timeout=30s:30秒后重新尝试
    # backup:仅在其他所有服务器宕机时使用
    # down:永久停用(维护用)
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://backend;
        proxy_next_upstream error timeout http_500 http_502 http_503;
        proxy_next_upstream_tries 3;        # 最多尝试3个不同的服务器
        proxy_next_upstream_timeout 10s;    # 超时
    }
}

7. HTTPS / SSL 配置

7.1 Let's Encrypt 免费证书签发

# 安装 Certbot
sudo apt install certbot python3-certbot-nginx -y    # Ubuntu
sudo dnf install certbot python3-certbot-nginx -y    # Rocky/RHEL

# 签发证书(Nginx 自动配置)
sudo certbot --nginx -d example.com -d www.example.com

# 测试证书自动续期
sudo certbot renew --dry-run

# 确认自动续期定时任务
sudo systemctl status certbot.timer

7.2 SSL 手动配置(含优化)

# /etc/nginx/conf.d/example.com.conf
server {
    listen 80;
    server_name example.com www.example.com;
    # HTTP → HTTPS 重定向
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name example.com www.example.com;

    # SSL 证书路径
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # SSL 协议(仅允许 TLS 1.2 及以上)
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;

    # SSL 会话缓存(提升握手性能)
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;

    # OCSP Stapling(加速证书验证)
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 8.8.4.4 valid=300s;

    # 安全头部
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
    add_header X-Frame-Options DENY always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-XSS-Protection "1; mode=block" always;

    root /var/www/example.com/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}
TIP: 使用 Mozilla SSL Configuration Generator 可以根据服务器环境自动生成最优的 SSL 配置。

8. 安全配置

8.1 基本安全加固

# /etc/nginx/conf.d/security.conf(通用安全配置)

# 隐藏 Nginx 版本信息
server_tokens off;

# 请求大小限制(默认 1MB)
client_max_body_size 10M;

# 请求头/请求体超时
client_header_timeout 10s;
client_body_timeout 10s;
send_timeout 10s;

# 防止缓冲区溢出攻击
client_body_buffer_size 1K;
client_header_buffer_size 1k;
large_client_header_buffers 2 1k;

8.2 基于 IP 的访问控制

# 管理页面 IP 限制
location /admin/ {
    allow 10.0.0.0/8;           # 允许内部网络
    allow 192.168.1.100;         # 允许特定 IP
    deny all;                    # 拒绝其他所有

    proxy_pass http://127.0.0.1:8080;
}

# 封禁特定国家/IP段
# 使用 geo 模块
geo $blocked_ip {
    default 0;
    1.2.3.0/24 1;               # 要封禁的 IP 段
    5.6.7.0/24 1;
}

server {
    if ($blocked_ip) {
        return 403;
    }
}

8.3 Rate Limiting(请求限流)

# 在 http 块中定义 zone
http {
    # 每个 IP 限制每秒10个请求
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;

    # 每个 IP 限制并发连接数
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
}

# 在 server 块中应用
server {
    # 对 API 应用 Rate Limit
    location /api/ {
        limit_req zone=api_limit burst=20 nodelay;
        # burst=20:瞬间允许20个请求
        # nodelay:超出部分立即处理(不等待)

        limit_req_status 429;    # 超限时返回 429 响应

        proxy_pass http://backend;
    }

    # 登录页面(更严格的限制)
    location /login {
        limit_req zone=api_limit burst=5;
        limit_conn conn_limit 5;  # 限制并发5个连接

        proxy_pass http://backend;
    }
}

8.4 防御爬虫/抓取器

# 封禁恶意 User-Agent
if ($http_user_agent ~* (scrapy|curl|wget|python-requests|httpclient|Go-http-client)) {
    return 403;
}

# 封禁空 User-Agent
if ($http_user_agent = "") {
    return 403;
}

# 封禁特定 Referer(防盗链)
location ~* \.(jpg|jpeg|png|gif|webp)$ {
    valid_referers none blocked server_names *.example.com;
    if ($invalid_referer) {
        return 403;
    }
}

9. 性能优化

9.1 Gzip 压缩

http {
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;           # 压缩级别(1-9,推荐6)
    gzip_min_length 256;         # 仅压缩256字节以上
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/json
        application/javascript
        application/xml
        application/rss+xml
        application/atom+xml
        image/svg+xml
        font/woff
        font/woff2;
}

9.2 静态文件缓存

# 静态资源浏览器缓存
location ~* \.(jpg|jpeg|png|gif|ico|webp|avif)$ {
    expires 365d;
    add_header Cache-Control "public, immutable";
    access_log off;
}

location ~* \.(css|js)$ {
    expires 30d;
    add_header Cache-Control "public";
    access_log off;
}

location ~* \.(woff|woff2|ttf|otf|eot)$ {
    expires 365d;
    add_header Cache-Control "public, immutable";
    access_log off;
    add_header Access-Control-Allow-Origin "*";  # CORS(字体)
}

location ~* \.(html|htm)$ {
    expires 1h;
    add_header Cache-Control "public, must-revalidate";
}

9.3 代理缓存

http {
    # 定义代理缓存区域
    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m
                     max_size=1g inactive=60m use_temp_path=off;

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

            # 启用缓存
            proxy_cache my_cache;
            proxy_cache_valid 200 302 10m;   # 200、302 → 缓存10分钟
            proxy_cache_valid 404 1m;        # 404 → 缓存1分钟

            # 缓存状态头部(调试用)
            add_header X-Cache-Status $upstream_cache_status;

            # 缓存绕过条件
            proxy_cache_bypass $http_cache_control;
            proxy_no_cache $http_pragma;
        }
    }
}

9.4 Worker 进程调优

# 根据 CPU 核心数设置
worker_processes auto;          # 自动检测(推荐)

events {
    worker_connections 4096;    # 根据服务器规模调整
    use epoll;                  # Linux 最优事件模型
    multi_accept on;
}

http {
    # 文件描述符缓存
    open_file_cache max=10000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;
}
# 操作系统级调优(内核参数)
# 添加到 /etc/sysctl.conf
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_tw_reuse = 1

# Worker 进程的文件描述符限制
# /etc/security/limits.conf
# nginx soft nofile 65535
# nginx hard nofile 65535

# 或在 nginx.conf 的全局上下文中设置:
worker_rlimit_nofile 65535;

10. 日志配置与监控

10.1 自定义日志格式

http {
    # 详细日志格式(包含响应时间)
    log_format detailed '$remote_addr - $remote_user [$time_local] '
                        '"$request" $status $body_bytes_sent '
                        '"$http_referer" "$http_user_agent" '
                        '$request_time $upstream_response_time';

    # JSON 格式日志(适合 ELK/Loki 集成)
    log_format json_log escape=json '{'
        '"time":"$time_iso8601",'
        '"remote_addr":"$remote_addr",'
        '"request":"$request",'
        '"status":$status,'
        '"body_bytes_sent":$body_bytes_sent,'
        '"request_time":$request_time,'
        '"upstream_response_time":"$upstream_response_time",'
        '"http_referer":"$http_referer",'
        '"http_user_agent":"$http_user_agent"'
    '}';

    # 条件日志(不记录 2xx 响应)
    map $status $loggable {
        ~^[23] 0;
        default 1;
    }

    server {
        access_log /var/log/nginx/access.log detailed;
        # access_log /var/log/nginx/access.json json_log if=$loggable;
    }
}

10.2 日志轮转

# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 $(cat /var/run/nginx.pid)
    endscript
}

10.3 Nginx 状态监控(stub_status)

# 仅允许内部访问的状态页面
server {
    listen 8080;
    server_name localhost;

    location /nginx_status {
        stub_status on;
        allow 127.0.0.1;
        allow 10.0.0.0/8;
        deny all;
    }
}

# 输出示例:
# Active connections: 291
# server accepts handled requests
#  16630948 16630948 31070465
# Reading: 6 Writing: 179 Waiting: 106
# 查看状态
curl http://localhost:8080/nginx_status

# 集成 Prometheus 时使用 nginx-prometheus-exporter
# docker run -p 9113:9113 nginx/nginx-prometheus-exporter -nginx.scrape-uri=http://host:8080/nginx_status

11. 实战运维技巧

11.1 常用命令汇总

# 验证配置语法(修改后务必执行!)
sudo nginx -t

# 不中断服务应用配置
sudo systemctl reload nginx

# 重启服务(会中断)
sudo systemctl restart nginx

# 实时监控日志
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log

# 过滤特定状态码
tail -f /var/log/nginx/access.log | grep --line-buffered '" 500 '

# 查看连接状态
ss -tlnp | grep nginx

# 查看当前活跃连接数
ss -s | head -5

# 查看 Nginx 主进程/Worker 进程
ps aux | grep nginx

# 查看配置文件路径及模块
nginx -V 2>&1 | tr ' ' '\n' | grep -E "^--"

11.2 无中断配置变更流程

# 1. 修改配置文件
sudo nano /etc/nginx/conf.d/example.com.conf

# 2. 语法验证(必须!)
sudo nginx -t
# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful

# 3. 使用 reload 应用(零停机)
sudo systemctl reload nginx

# 如果存在语法错误:
# nginx: [emerg] unknown directive "servr" in /etc/nginx/conf.d/example.com.conf:2
# nginx: configuration file /etc/nginx/nginx.conf test failed
# → 不要执行 reload,先修复错误!

11.3 常见问题与解决方法

症状 原因 解决方法
502 Bad Gateway 后端服务器宕机或 Socket 错误 检查后端进程,确认 proxy_pass 地址
504 Gateway Timeout 后端响应延迟 增大 proxy_read_timeout
413 Request Entity Too Large 上传大小超限 增大 client_max_body_size
403 Forbidden 文件权限或 SELinux 检查文件所有者/权限,确认 SELinux 上下文
301 重定向循环 HTTP↔HTTPS 配置冲突 分离 server 块,检查 $scheme 条件
实时日志不显示 access_log off; 或缓冲 检查 location 块的日志配置

12. 配置文件检查清单

在将 Nginx 部署到生产服务器之前,请务必检查以下各项:

  • 基本安全:是否设置了 server_tokens off;
  • HTTPS:所有 HTTP 流量是否重定向到 HTTPS
  • SSL 协议:是否仅允许 TLS 1.2 及以上版本
  • 安全头部:是否设置了 HSTS、X-Frame-Options、X-Content-Type-Options
  • 文件访问:是否阻止了 .git.env 等隐藏文件的访问
  • 上传限制client_max_body_size 是否设置了合适的值
  • Rate Limiting:API、登录等敏感路径是否设置了限流
  • Gzip 压缩:是否对文本类响应启用了压缩
  • 缓存:静态文件是否设置了适当的 expires
  • 日志:是否按站点分离了日志并配置了日志轮转
  • Default Server:是否处理了未匹配的请求(return 444;
  • 超时proxy_read_timeout 等是否设置了合适的超时值
  • 备份:配置文件是否有备份和版本管理(推荐 Git)

结语:Nginx 的配置就是实力的体现

Nginx 安装简单,但要真正运维好它,需要对配置有深入的理解。本指南中涵盖的内容都是基于实际工作中最常遇到的场景编写的。

核心要点总结如下:

  • 打好基础 - 理解 nginx.conf 的块结构和继承关系。
  • 牢记 location 优先级 - =^~~/~* → 普通前缀。仅凭这一点就能解决大多数路由问题。
  • 修改前务必执行 nginx -t - 配置错误直接导致服务故障。语法验证不是可选项,而是必选项。
  • reload ≠ restart - reload 是零停机更新,restart 会导致服务中断。
  • 安全要从一开始做起 - HTTPS、安全头部、Rate Limiting 应在运营开始前就配置好。
  • 日志是宝贵资产 - 配置自定义日志格式并定期分析,对故障预防和性能优化大有裨益。

请根据自己的环境修改本指南中的配置示例并加以实践。随着实战经验的积累,Nginx 配置将变得越来越得心应手,复杂的架构也能自信地驾驭。