常见nginx配置

Nginx 配置手册

日常使用配置整理,持续更新。

格式:配置说明 + 示例代码 + 注意事项。


目录


基础概念

Nginx 是高性能的 HTTP 服务器 / 反向代理服务器。配置文件默认路径:

系统 路径
Linux(通用) /etc/nginx/nginx.conf
Linux(站点配置) /etc/nginx/conf.d/*.conf/etc/nginx/sites-enabled/
Windows nginx安装目录/conf/nginx.conf

常用命令:

bash 复制代码
nginx -t                  # 检查配置语法
nginx -s reload           # 热重载配置(不中断服务)
nginx -s stop             # 快速停止
systemctl reload nginx    # Linux systemd 热重载

配置文件结构

nginx 复制代码
# 全局块
worker_processes auto;

events {
    worker_connections 1024;
}

http {
    # http 块(全局 HTTP 设置)
    include       mime.types;
    default_type  application/octet-stream;

    server {
        # server 块(虚拟主机)
        listen 80;
        server_name example.com;

        location / {
            # location 块(路由匹配)
            root /var/www/html;
            index index.html;
        }
    }
}

层级说明:

  • 全局块:影响 Nginx 整体行为,如工作进程数
  • events:网络连接处理模型
  • http:HTTP 协议相关设置,可包含多个 server
  • server:虚拟主机,监听端口和域名
  • location:URL 路由匹配,处理具体请求

常用配置

8. 静态文件服务(Static File Serving)

配置:

nginx 复制代码
# 正射影像
location /dom {
    # CORS 跨域配置
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
    
    # 静态文件配置
    alias D:\\kszyjg_data\\dom\\;   # 指定文件目录(Windows 路径)
    index index.html index.htm;    # 默认文件
    
    expires 30d;                 # 缓存 30 天
}

说明:

  • location /dom:匹配 /dom 路径的请求
  • alias:指定实际文件目录(替代 root
  • expires:设置浏览器缓存时间

关键区别:root vs alias

nginx 复制代码
# root 方式(URI 附加到路径)
location /images {
    root /var/www;  # 实际路径:/var/www/images/
}

# alias 方式(直接替换路径)
location /images {
    alias /var/www/img/;  # 实际路径:/var/www/img/
}

CORS 跨域配置详解:

  • Access-Control-Allow-Origin: *:允许所有域名访问
  • Access-Control-Allow-Methods:允许的 HTTP 方法
  • Access-Control-Allow-Headers:允许的自定义请求头

静态文件优化:

nginx 复制代码
location /static/ {
    alias /var/www/static/;
    expires 30d;                 # 缓存 30 天
    add_header Cache-Control "public";  # 公共缓存
    add_header Last-Modified $date_gmt;  # 最后修改时间
    add_header ETag $etag;        # ETag 校验
}

注意事项:

  • 路径分隔符 :Windows 使用 \\,Linux 使用 /
  • 目录权限:确保 Nginx 有读取权限
  • 缓存控制expires 减少重复请求
  • CORS 安全 :生产环境建议指定具体域名(非 *

完整示例:

nginx 复制代码
server {
    listen 80;
    server_name example.com;
    
    # 静态文件服务
    location /dom {
        add_header 'Access-Control-Allow-Origin' 'https://example.com';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        alias D:\\kszyjg_data\\dom\\;
        index index.html;
        expires 30d;
    }
    
    # 图片服务
    location /images/ {
        alias /var/www/images/;
        expires 365d;  # 图片缓存 1 年
    }
}

9. 错误页面配置(error_page)

配置:

nginx 复制代码
# 404 错误页面
error_page   404              /404.html; 
location = /404.html {
    root   html; 
}

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

说明:

  • error_page:指定错误码对应的错误页面
  • location = /404.html:精确匹配 /404.html 路径
  • root html:错误页面所在目录(相对于 Nginx 安装目录)

常见错误页面配置:

nginx 复制代码
# 自定义错误页面
error_page 400 /400.html;  # 错误请求
error_page 403 /403.html;  # 禁止访问
error_page 404 /404.html;  # 页面不存在
error_page 500 502 503 504 /50x.html;  # 服务器错误

# 错误页面 location 配置
location = /404.html {
    root /usr/share/nginx/html;
    internal;  # 只允许内部重定向访问
}

location = /50x.html {
    root /usr/share/nginx/html;
    internal;
}

注意事项:

  • 路径问题:确保错误页面文件存在
  • internal 指令:限制错误页面只能内部访问
  • 自定义页面:可以设计友好的错误页面提升用户体验
  • 测试验证 :使用 curl -I http://yourdomain.com/nonexistent 测试 404 页面

完整示例:

nginx 复制代码
server {
    listen 80;
    server_name example.com;
    
    # 错误页面配置
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    
    # 错误页面 location
    location = /404.html {
        root /usr/share/nginx/html;
        internal;
    }
    
    location = /50x.html {
        root /usr/share/nginx/html;
        internal;
    }
    
    location / {
        root /var/www/html;
        index index.html;
    }
}
复制代码
# 最小配置
server {
    root /usr/share/nginx/html;
    error_page 404 /404.html;

    location = /404.html {
        root /var/www/custom_errors;   # 自定义路径
        internal;                      # 仅内部访问
    }
}

10. 路径配置详解(root vs alias,斜杠区别)

核心区别:

指令 路径处理方式 示例
root URI 附加到 root 路径后 location /images + root /var/www/var/www/images/
alias 直接替换 location 路径 location /images + alias /var/www/img//var/www/img/

斜杠的影响:

  1. location 后面的斜杠
nginx 复制代码
location /test {        # 匹配 /test 和 /test/xxx
    alias /var/www/;
}

location /test/ {       # 只匹配 /test/xxx,不匹配 /test
    alias /var/www/;
}
  1. alias 后面的斜杠
nginx 复制代码
# 推荐:alias 路径以斜杠结尾
alias /var/www/test/;  # 正确

# 不推荐:可能导致路径拼接问题
alias /var/www/test;   # 警告:建议使用斜杠结尾
  1. root 后面的斜杠
nginx 复制代码
# root 路径可以以斜杠结尾,也可以不以斜杠结尾
root /var/www;     # 正确
root /var/www/;    # 也正确,效果相同

实际案例对比:

nginx 复制代码
# 案例 1:root 方式
location /static/ {
    root /var/www;  # 访问 /static/logo.png → /var/www/static/logo.png
}

# 案例 2:alias 方式
location /static/ {
    alias /var/www/assets/;  # 访问 /static/logo.png → /var/www/assets/logo.png
}

# 案例 3:无斜杠 location
location /static {
    alias /var/www/assets/;  # 访问 /static/logo.png → /var/www/assets//logo.png(可能有问题)
}

最佳实践:

nginx 复制代码
# 推荐写法
location /static/ {
    alias /var/www/assets/;  # location 和 alias 都以斜杠结尾
    index index.html;
}

# 或者
location /static/ {
    root /var/www;  # root 方式,路径会自动拼接
    index index.html;
}

注意事项:

  • alias 必须以斜杠结尾:避免路径拼接问题
  • location 匹配/test 匹配 /test/test//test/ 只匹配 /test/
  • 路径权限:确保 Nginx 有读取权限
  • Windows 路径 :使用 \\/(推荐)

完整示例:

nginx 复制代码
server {
    listen 80;
    server_name example.com;
    
    # 方式 1:root(推荐用于常规场景)
    location /static/ {
        root /var/www;  # /static/logo.png → /var/www/static/logo.png
    }
    
    # 方式 2:alias(推荐用于路径重写场景)
    location /static/ {
        alias /var/www/assets/;  # /static/logo.png → /var/www/assets/logo.png
    }
    
    # Windows 路径
    location /app/ {
        alias D:\\www\\app\\;  # Windows 路径使用双反斜杠
    }
}

11. include 指令详解

配置:

nginx 复制代码
include nginx_cors;  # 包含 CORS 配置文件

说明:

  • include:将其他配置文件包含到当前配置中
  • nginx_cors:CORS(跨域资源共享)配置文件

常见 include 用法:

nginx 复制代码
# 1. 包含 MIME 类型定义
include mime.types;

# 2. 包含配置文件(相对路径)
include nginx_cors;           # 相对于 nginx.conf 目录
include conf/nginx_cors;      # 相对于 nginx.conf 目录的 conf/ 子目录

# 3. 包含配置文件(绝对路径)
include /etc/nginx/conf.d/*.conf;  # 绝对路径

# 4. 包含通配符匹配的文件
include conf/vhost/*.conf;    # 包含 vhost 目录下所有 .conf 文件

nginx_cors 文件内容示例:

nginx 复制代码
# conf/nginx_cors
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;

用户配置分析:

nginx 复制代码
location /test {
    include nginx_cors;                  # 包含 CORS 配置
    alias D:\kszyjg\ks-web-ca\yzt\dist;  # 静态文件目录(注意:路径缺少结尾斜杠)
    index  index.html index.htm;	
}

问题修正:

nginx 复制代码
location /test/ {                        # 建议加斜杠
    include nginx_cors;                  # 包含 CORS 配置
    alias D:\kszyjg\ks-web-ca\yzt\dist\;  # 建议加斜杠结尾
    index  index.html index.htm;	
}

注意事项:

  • 路径问题:确保包含的文件存在
  • 相对路径:相对于 nginx.conf 所在目录
  • 文件内容:被包含的文件应该是合法的 Nginx 配置片段
  • 性能影响:过多 include 可能影响配置加载速度

完整示例:

nginx 复制代码
http {
    # 包含 MIME 类型
    include mime.types;
    
    # 包含 CORS 配置
    include conf/nginx_cors;
    
    server {
        listen 80;
        server_name example.com;
        
        location /api/ {
            include nginx_cors;  # 为 API 路径启用 CORS
            proxy_pass http://backend;
        }
        
        location /static/ {
            include nginx_cors;  # 为静态资源启用 CORS
            alias /var/www/static/;
        }
    }
}

12. 限流配置(limit_req)

配置:

nginx 复制代码
# 定义限流区域
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

server {
    location /api/ {
        # 应用限流
        limit_req zone=one burst=5 nodelay;
    }
}

说明:

  • limit_req_zone:定义限流区域
    • $binary_remote_addr:限流键(按 IP 地址)
    • zone=one:10m:共享内存区域名称和大小
    • rate=1r/s:限流速率(每秒 1 个请求)
  • limit_req:应用限流
    • zone=one:使用名为 one 的限流区域
    • burst=5:允许突发 5 个请求
    • nodelay:不延迟处理突发请求

限流参数详解:

nginx 复制代码
# 1. 基本限流(每秒 1 个请求)
limit_req_zone $binary_remote_addr zone=basic:10m rate=1r/s;
limit_req zone=basic;

# 2. 带突发的限流(允许突发 5 个请求)
limit_req_zone $binary_remote_addr zone=burst:10m rate=1r/s;
limit_req zone=burst burst=5;

# 3. 不带延迟的突发限流(突发请求立即处理)
limit_req_zone $binary_remote_addr zone=nodelay:10m rate=1r/s;
limit_req zone=nodelay burst=5 nodelay;

# 4. 自定义限流键(按用户 ID 限流)
limit_req_zone $http_x_user_id zone=user:10m rate=10r/s;
limit_req zone=user;

实际案例:

nginx 复制代码
# 案例 1:API 接口限流(防止刷接口)
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

server {
    location /api/ {
        limit_req zone=api burst=20 nodelay;
        proxy_pass http://backend;
    }
}

# 案例 2:登录接口限流(防止暴力破解)
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;

server {
    location /login {
        limit_req zone=login burst=5 nodelay;
        proxy_pass http://auth_backend;
    }
}

# 案例 3:按 User-Agent 限流(防止爬虫)
limit_req_zone $http_user_agent zone=bot:10m rate=5r/s;

server {
    location / {
        limit_req zone=bot burst=10;
        root /var/www/html;
    }
}

注意事项:

  • 内存占用zone=one:10m 可存储约 16 万个 IP 地址
  • 突发请求burst 控制允许突发的请求数量
  • 延迟处理 :默认突发请求会延迟处理,加 nodelay 则立即处理
  • 返回状态码:限流时返回 503(Service Temporarily Unavailable)
  • 测试验证 :使用 abwrk 工具进行压力测试

完整示例:

nginx 复制代码
http {
    # 定义限流区域
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;
    
    server {
        listen 80;
        server_name example.com;
        
        # API 接口限流
        location /api/ {
            limit_req zone=api burst=20 nodelay;
            proxy_pass http://api_backend;
        }
        
        # 登录接口限流
        location /login {
            limit_req zone=login burst=5 nodelay;
            proxy_pass http://auth_backend;
        }
        
        # 静态文件不限流
        location /static/ {
            alias /var/www/static/;
        }
    }
}

限流测试:

bash 复制代码
# 使用 ab 进行压力测试
ab -n 100 -c 10 http://example.com/api/test

# 使用 wrk 进行压力测试
wrk -t 10 -c 100 -d 10s http://example.com/api/test

13. 反向代理配置(proxy_pass)

基本配置:

nginx 复制代码
location /api/ {
    proxy_pass http://127.0.0.1:8080/;   # 代理到后端服务
}

完整推荐配置(生产环境):

nginx 复制代码
location /api/ {
    proxy_pass http://127.0.0.1:8080/;

    # 传递真实客户端 IP
    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_set_header Host $host;

    # 超时设置
    proxy_connect_timeout 5s;   # 连接后端超时
    proxy_send_timeout 60s;      # 发送请求超时
    proxy_read_timeout 60s;      # 读取响应超时

    # 关闭缓冲(实时响应,适用于流式接口)
    proxy_buffering off;

    # 或开启缓冲(高性能场景)
    # proxy_buffering on;
    # proxy_buffer_size 16k;
    # proxy_buffers 4 64k;
}

proxy_pass 后面有无斜杠的区别(重点):

nginx 复制代码
# 情况 1:proxy_pass 后面有斜杠 → 替换 location 路径
location /api/ {
    proxy_pass http://127.0.0.1:8080/;
}
# 请求 /api/user/list → 转发到 http://127.0.0.1:8080/user/list

# 情况 2:proxy_pass 后面无斜杠 → 保留 location 路径
location /api/ {
    proxy_pass http://127.0.0.1:8080;
}
# 请求 /api/user/list → 转发到 http://127.0.0.1:8080/api/user/list
proxy_pass 写法 请求 URL 转发到后端 URL
http://xxx:8080/ (有斜杠) /api/user http://xxx:8080/user
http://xxx:8080 (无斜杠) /api/user http://xxx:8080/api/user
http://xxx:8080/app/ (有路径) /api/user http://xxx:8080/app/user

WebSocket 代理配置:

nginx 复制代码
location /ws/ {
    proxy_pass http://127.0.0.1:8080/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

注意事项:

  • 斜杠问题proxy_pass 后面有无斜杠行为完全不同,见上表
  • Host 头 :务必设置 proxy_set_header Host $host,否则后端拿到的是 127.0.0.1
  • 超时时间:根据接口实际耗时调整,避免过早断开
  • 测试验证curl -v http://yourdomain.com/api/test 查看转发结果

14. 负载均衡与权重配置(upstream)

通过 upstream 定义后端服务器组,实现请求分发。

方式一:默认轮询(权重均等)
nginx 复制代码
upstream backend {
    server 127.0.0.1:8080;
    server 127.0.0.1:8081;
    server 127.0.0.1:8082;
}

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

每个服务按 1:1:1 的比例接收请求,适合所有后端性能相同的场景。

方式二:权重配置(weight
nginx 复制代码
upstream backend {
    server 127.0.0.1:8080 weight=3;   # 接收 3/6 = 50% 请求
    server 127.0.0.1:8081 weight=2;   # 接收 2/6 = 33% 请求
    server 127.0.0.1:8082 weight=1;   # 接收 1/6 = 17% 请求
}

weight 值越大,分到的请求越多。总权重 = 3+2+1 = 6。

方式三:IP 哈希(ip_hash,Session 保持)
nginx 复制代码
upstream backend {
    ip_hash;   # 同一 IP 始终访问同一后端
    server 127.0.0.1:8080;
    server 127.0.0.1:8081;
}

适用于需要 Session 保持 的场景(未做 Session 共享时)。

方式四:最少连接(least_conn
nginx 复制代码
upstream backend {
    least_conn;   # 请求分配给当前连接数最少的服务器
    server 127.0.0.1:8080;
    server 127.0.0.1:8081;
}

适用于请求处理时间差异较大的场景,避免某台服务器堆积。

方式五:备用服务器(backup
nginx 复制代码
upstream backend {
    server 127.0.0.1:8080 weight=3;
    server 127.0.0.1:8081 weight=2;
    server 127.0.0.1:8082 backup;   # 主服务器都挂了才启用
}
方式六:健康检查参数
nginx 复制代码
upstream backend {
    server 127.0.0.1:8080 weight=3 max_fails=2 fail_timeout=30s;
    server 127.0.0.1:8081 weight=2 max_fails=2 fail_timeout=30s;
    server 127.0.0.1:8082 weight=1 max_fails=2 fail_timeout=30s;
}
  • max_fails:在 fail_timeout 时间内,失败多少次标记为不可用(默认 1)
  • fail_timeout:失败超时时间,同时也是标记为不可用后的冷却时间(默认 10s)

配置方式对照表:

配置方式 关键指令 适用场景
默认轮询 不加 weight 所有后端性能相同
权重轮询 weight=N 后端性能不均,高性能多分请求
IP 哈希 ip_hash 需要 Session 保持
最少连接 least_conn 请求处理时间差异大
备用服务器 backup 主备切换,高可用

完整生产级示例:

nginx 复制代码
# 定义后端服务器组
upstream backend {
    # 权重配置:性能好的服务器权重高
    server 127.0.0.1:8080 weight=3 max_fails=2 fail_timeout=30s;
    server 127.0.0.1:8081 weight=2 max_fails=2 fail_timeout=30s;
    server 127.0.0.1:8082 weight=1 max_fails=2 fail_timeout=30s;
    server 127.0.0.1:8083 backup;   # 备用服务器
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://backend;

        # 传递请求头
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;

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

最后更新:2026-06-09

相关推荐
杰克逊的日记1 小时前
如何部署EDA工具及运维
运维·eda运维
上海达策TECHSONIC1 小时前
零售ERP选型解析:SAP Business One 适配成长型零售企业的核心逻辑
大数据·运维·人工智能·云计算·运维开发·零售
蜡笔婧萱1 小时前
磁盘监控 + Web 服务巡检自动化脚本实训任务
运维·自动化
折哥的程序人生 · 物流技术专研1 小时前
Tomcat 严重警告:JDBC 驱动未注销 + 工作线程泄漏 —— 原因、影响与彻底修复(生产级终极指南)
java·运维·数据库·mysql·oracle·tomcat
Techblog of HaoWANG1 小时前
智巡守卫:多模态巡检智能体算法服务端设计与实现——基于Ollama+Qwen3.5的自动化巡检报告生成系统
运维·人工智能·算法·目标检测·自动化·边缘计算
hweiyu002 小时前
Linux命令:newgrp
linux·运维·服务器
Full Stack Developme2 小时前
计算机加密与解密的历史
运维·服务器·网络·云计算
IPDEEP全球代理2 小时前
静态住宅ip哪家好?2026年静态住宅ip测评
运维·服务器·网络
哆啦A梦15882 小时前
服务器基础知识
运维·服务器