Nginx 的多个场景配置

Nginx 的多个场景配置

本文汇总了生产环境中最常见的 Nginx 配置场景,涵盖反向代理、负载均衡、静态资源优化、安全加固、特殊业务适配等核心场景,并提供可直接复用的配置模板。

一、基础配置与核心模块

1.1 最小化生产配置

nginx 复制代码
# /etc/nginx/nginx.conf
user nginx;                  # 运行用户(建议与业务用户隔离,如 www-data)
worker_processes auto;       # 工作进程数(建议与 CPU 核心数一致)
error_log /var/log/nginx/error.log warn;  # 全局错误日志级别
pid /run/nginx.pid;

events {
    worker_connections 10240; # 单进程最大连接数(需配合系统 ulimit 调整)
    use epoll;               # 高效事件驱动模型(Linux 推荐)
}

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

    # 自定义日志格式(含代理链 IP、请求耗时)
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for" '
                    '$request_time $upstream_response_time';
    access_log /var/log/nginx/access.log main;

    sendfile        on;
    tcp_nopush      on;    # 配合 sendfile 优化 TCP 包发送
    tcp_nodelay     on;    # 禁用 Nagle 算法(低延迟场景必备)
    keepalive_timeout  65; # 长连接超时时间

    # 引入子配置(模块化管理)
    include /etc/nginx/conf.d/*.conf;
}

二、反向代理场景

2.1 代理单节点 Web 服务(Tomcat/Node.js 等)

nginx 复制代码
# /etc/nginx/conf.d/proxy-web.conf
server {
    listen 80;
    server_name web.example.com;

    location / {
        proxy_pass http://127.0.0.1:8080;  # 后端服务地址
        proxy_set_header Host $host;        # 传递客户端 Host
        proxy_set_header X-Real-IP $remote_addr;  # 真实客户端 IP
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  # 代理链 IP
        proxy_set_header X-Forwarded-Proto $scheme;  # 协议(http/https)

        # 超时配置(按需调整,避免业务超时被 Nginx 中断)
        proxy_connect_timeout 30s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;

        # 缓冲区配置(大响应场景建议开启)
        proxy_buffer_size 16k;
        proxy_buffers 4 64k;
        proxy_busy_buffers_size 128k;
    }

    # 静态资源单独代理(减轻后端压力)
    location ~* \.(jpg|jpeg|png|css|js)$ {
        proxy_pass http://127.0.0.1:8080;
        expires 7d;  # 静态资源缓存 7 天
        add_header Cache-Control "public, max-age=604800";
    }
}

2.2 代理 WebSocket 服务(RabbitMQ/即时通讯)

nginx 复制代码
# /etc/nginx/conf.d/proxy-websocket.conf
server {
    listen 80;
    server_name ws.example.com;

    location /ws {
        proxy_pass http://127.0.0.1:15674/ws;  # WebSocket 后端地址(如 RabbitMQ)
        
        # WebSocket 协议升级核心配置
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        
        # 长连接超时(需大于后端心跳间隔)
        proxy_connect_timeout 1d;
        proxy_send_timeout 1d;
        proxy_read_timeout 1d;
    }
}

2.3 代理 HTTPS 后端服务(SSL 透传)

nginx 复制代码
# /etc/nginx/conf.d/proxy-https.conf
server {
    listen 443 ssl;
    server_name api.example.com;

    # 客户端 <-> Nginx 之间的 SSL 配置
    ssl_certificate /etc/nginx/ssl/api.crt;
    ssl_certificate_key /etc/nginx/ssl/api.key;
    ssl_trusted_certificate /etc/nginx/ssl/ca.crt;  # 信任链证书

    ssl_protocols TLSv1.2 TLSv1.3;  # 仅启用安全协议
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers on;

    # 代理到后端 HTTPS 服务
    location / {
        proxy_pass https://192.168.1.100:8443;
        proxy_ssl_verify off;  # 生产环境建议开启并配置 CA
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

三、负载均衡场景

3.1 基础轮询 + 健康检查

nginx 复制代码
# /etc/nginx/conf.d/loadbalance.conf
http {
    upstream backend_servers {
        server 192.168.1.101:8080;
        server 192.168.1.102:8080;
        server 192.168.1.103:8080 down;  # 手动下线
        
        # 健康检查(需 ngx_http_upstream_check_module 模块)
        check interval=3000 rise=2 fall=3 timeout=1000 type=http;
        check_http_send "HEAD /health HTTP/1.0\r\n\r\n";
        check_http_expect_alive http_2xx http_3xx;
    }

    server {
        listen 80;
        server_name lb.example.com;

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

            # 失败时切换节点
            proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
        }
    }
}

3.2 加权负载均衡(按服务器性能分配)

nginx 复制代码
upstream backend_servers {
    server 192.168.1.101:8080 weight=3;  # 处理 3/6 请求
    server 192.168.1.102:8080 weight=2;  # 处理 2/6 请求
    server 192.168.1.103:8080 weight=1;  # 处理 1/6 请求
}

3.3 IP 哈希(会话保持)

nginx 复制代码
upstream backend_servers {
    ip_hash;  # 同一 IP 固定到同一节点
    server 192.168.1.101:8080;
    server 192.168.1.102:8080;
    server 192.168.1.103:8080 backup;  # 备份节点
}

四、静态资源优化场景

4.1 静态资源服务器(缓存 + 压缩 + 防盗链)

nginx 复制代码
# /etc/nginx/conf.d/static.conf
server {
    listen 80;
    server_name static.example.com;
    root /data/static;  # 静态资源根目录

    autoindex off;  # 关闭目录浏览

    # 按文件类型配置缓存策略
    location ~* \.(jpg|jpeg|png|gif|ico|svg)$ {
        expires 30d;
        add_header Cache-Control "public, max-age=2592000";
    }
    location ~* \.(css|js)$ {
        expires 7d;
        add_header Cache-Control "public, max-age=604800";
    }
    location ~* \.(html|htm)$ {
        expires 1h;
        add_header Cache-Control "public, max-age=3600";
    }

    # Gzip 压缩(减少传输大小)
    gzip on;
    gzip_types text/css text/javascript text/plain application/json image/svg+xml;
    gzip_min_length 1k;
    gzip_comp_level 5;

    # 防盗链(仅允许指定域名引用)
    location ~* \.(jpg|jpeg|png|gif)$ {
        valid_referers none blocked example.com *.example.com;
        if ($invalid_referer) {
            return 403;
        }
    }
}

4.2 大文件下载优化(断点续传 + 限速)

nginx 复制代码
# /etc/nginx/conf.d/download.conf
server {
    listen 80;
    server_name download.example.com;
    root /data/downloads;

    location / {
        # 断点续传支持
        add_header Accept-Ranges bytes;

        # 大文件传输优化
        sendfile on;
        tcp_nopush on;
        aio on;
        directio 4m;          # 大于 4M 的文件直接 I/O
        output_buffers 1 128k;

        # 限速(避免带宽耗尽)
        limit_rate 10m;       # 单连接限速 10MB/s
        limit_rate_after 50m; # 前 50MB 不限速
    }
}

五、安全加固场景

5.1 强化 HTTPS 配置(TLS 1.2+ + HSTS)

nginx 复制代码
# /etc/nginx/conf.d/https.conf
server {
    listen 443 ssl;
    server_name secure.example.com;

    ssl_certificate /etc/nginx/ssl/secure.crt;
    ssl_certificate_key /etc/nginx/ssl/secure.key;
    ssl_trusted_certificate /etc/nginx/ssl/ca.crt;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers on;

    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # 强制客户端使用 HTTPS(HSTS)
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # 防 XSS、点击劫持、MIME 嗅探
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
    }
}

# HTTP 强制跳转 HTTPS
server {
    listen 80;
    server_name secure.example.com;
    return 301 https://$host$request_uri;
}

5.2 访问控制(IP 白名单 + 密码认证)

nginx 复制代码
# /etc/nginx/conf.d/access-control.conf
server {
    listen 80;
    server_name admin.example.com;

    location /admin {
        # IP 白名单
        allow 192.168.1.0/24;
        allow 123.123.123.123;
        deny all;

        # 密码认证(需先执行 htpasswd -c .htpasswd admin)
        auth_basic "Admin Area";
        auth_basic_user_file /etc/nginx/conf.d/.htpasswd;

        proxy_pass http://127.0.0.1:8080/admin;
    }
}

5.3 防 DDoS 配置(限流 + 连接数限制)

nginx 复制代码
# /etc/nginx/conf.d/anti-ddos.conf
http {
    # 基于 IP 的请求限流
    limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
    # 基于 IP 的连接数限制
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

    server {
        listen 80;
        server_name api.example.com;

        location / {
            limit_req zone=req_limit burst=20 nodelay;  # 突发 20 个请求不延迟
            limit_conn conn_limit 10;                 # 单 IP 最大 10 个连接
            limit_conn_status 503;

            proxy_pass http://backend_servers;
        }

        # 敏感接口更严格限流
        location /api/payment {
            limit_req zone=req_limit rate=5r/s burst=10;
            proxy_pass http://backend_servers;
        }
    }
}

六、特殊场景配置

6.1 反向代理 FastDFS 分布式存储

nginx 复制代码
# /etc/nginx/conf.d/fastdfs.conf
server {
    listen 80;
    server_name fdfs.example.com;

    # 多组动态匹配(group1、group2...)
    location ~ ^/group([0-9])/M00/ {
        alias /data/fastdfs/storage/data/group$1/M00/;
        autoindex off;
        expires 30d;

        # 防盗链
        valid_referers none blocked *.example.com;
        if ($invalid_referer) {
            return 403;
        }
    }
}

6.2 适配 SPA 应用(前端路由重写)

nginx 复制代码
# /etc/nginx/conf.d/spa.conf
server {
    listen 80;
    server_name spa.example.com;
    root /data/spa/dist;
    index index.html;

    # 前端路由重写(所有路径指向 index.html)
    location / {
        try_files $uri $uri/ /index.html;
    }

    # API 请求代理到后端
    location /api {
        proxy_pass http://127.0.0.1:8080/api;
        proxy_set_header Host $host;
    }
}

6.3 灰度发布(按 Cookie/Header 分流)

nginx 复制代码
# /etc/nginx/conf.d/gray-release.conf
http {
    upstream gray_servers {
        server 192.168.1.201:8080;  # 灰度环境
    }
    upstream prod_servers {
        server 192.168.1.101:8080;  # 生产环境
    }

    server {
        listen 80;
        server_name app.example.com;

        location / {
            # 按 Cookie 分流(灰度用户携带 gray=1)
            if ($cookie_gray = "1") {
                proxy_pass http://gray_servers;
                break;
            }
            # 按 Header 分流(内部测试)
            if ($http_x_gray = "true") {
                proxy_pass http://gray_servers;
                break;
            }
            # 默认走生产
            proxy_pass http://prod_servers;

            proxy_set_header Host $host;
        }
    }
}

七、配置管理与最佳实践

7.1 模块化配置拆分

复制代码
/etc/nginx/
├── nginx.conf          # 主配置
├── conf.d/
│   ├── proxy-web.conf  # Web 代理配置
│   ├── static.conf     # 静态资源配置
│   ├── ssl.conf        # SSL 通用配置(通过 include 引入)
│   └── ...
├── ssl/                # 证书目录
│   ├── example.crt
│   └── example.key
└── snippets/           # 配置片段(限流、缓存等)
    ├── limit.conf
    └── cache.conf

7.2 常用运维命令

命令 作用
nginx -t 配置语法检查
nginx -s reload 平滑重启(不中断连接)
nginx -V 查看编译参数(确认已安装模块)
curl http://localhost/nginx-status 监控连接状态(需启用 stub_status)

7.3 性能优化建议

  1. worker_processes :设置为 CPU 核心数(grep ^processor /proc/cpuinfo | wc -l)。
  2. worker_connections :结合系统 ulimit -n 调整(建议 10240+)。
  3. 缓存策略 :静态资源启用浏览器缓存 + Nginx 本地缓存(proxy_cache)。
  4. 日志级别 :生产环境调整为 warn,避免日志 IO 阻塞。
  5. 模块精简 :编译时仅保留必需模块(如 --without-http_autoindex_module)。

可扩展场景:Nginx + Lua 动态逻辑、WAF 集成、HTTP/2 配置、Kubernetes ingress 适配等。

相关推荐
sunfove2 小时前
光网络的立交桥:光开关 (Optical Switch) 原理与主流技术解析
网络
HIT_Weston2 小时前
93、【Ubuntu】【Hugo】搭建私人博客:面包屑(一)
linux·运维·ubuntu
cuijiecheng20183 小时前
Linux下Beyond Compare过期
linux·运维·服务器
喵叔哟3 小时前
20.部署与运维
运维·docker·容器·.net
HIT_Weston3 小时前
92、【Ubuntu】【Hugo】搭建私人博客:侧边导航栏(六)
linux·运维·ubuntu
CodeAllen嵌入式3 小时前
Windows 11 本地安装 WSL 支持 Ubuntu 24.04 完整指南
linux·运维·ubuntu
Kevin Wang7274 小时前
欧拉系统服务部署注意事项
网络·windows
min1811234564 小时前
深度伪造内容的检测与溯源技术
大数据·网络·人工智能
汤愈韬5 小时前
Full Cone Nat
网络·网络协议·网络安全·security·huawei
zbtlink5 小时前
现在还需要带电池的路由器吗?是用来干嘛的?
网络·智能路由器