Nginx代理配置详解:正向代理与反向代理完全指南

发布于:2025-08-18 ⋅ 阅读:(15) ⋅ 点赞:(0)

系列文章索引:

前言

在现代网络架构中,代理服务器扮演着至关重要的角色。Nginx作为一款高性能的Web服务器,其代理功能被广泛应用于各种场景,从企业内网访问控制到大型网站负载均衡。本文将深入探讨Nginx的正向代理和反向代理配置,通过实际案例帮助你掌握代理配置的核心技能。

代理服务器本质上是一个中间人,负责在客户端和服务器之间传递请求和响应。根据代理的方向不同,可以分为正向代理和反向代理,它们在应用场景和工作原理上有着本质的区别。

一、代理服务器基础概念

1.1 什么是代理服务器

代理服务器(Proxy Server)是位于客户端和目标服务器之间的中间服务器,它接收客户端的请求,然后转发给目标服务器,并将服务器的响应返回给客户端。

代理服务器的基本功能:

  • 请求转发:将客户端请求转发到目标服务器
  • 响应缓存:缓存服务器响应,提高访问速度
  • 访问控制:控制客户端对特定资源的访问
  • 内容过滤:过滤不合适的内容
  • 安全防护:隐藏真实IP地址,提供安全屏障

1.2 正向代理 vs 反向代理

正向代理(Forward Proxy)

工作原理:

  • 客户端明确知道代理服务器的存在
  • 客户端配置代理服务器地址
  • 代理服务器代表客户端访问外部网络
  • 服务器不知道真实客户端的IP地址

应用场景:

  • 企业内网访问外网
  • 突破网络访问限制
  • 访问控制与审计
  • 缓存加速

工作流程:

客户端 → 代理服务器 → 目标服务器
反向代理(Reverse Proxy)

工作原理:

  • 客户端不知道代理服务器的存在
  • 客户端直接访问代理服务器
  • 代理服务器代表服务器接收客户端请求
  • 客户端不知道真实服务器的IP地址

应用场景:

  • 负载均衡
  • 安全防护
  • SSL卸载
  • 缓存加速

工作流程:

客户端 ← 代理服务器 ← 目标服务器
对比总结
特性 正向代理 反向代理
服务对象 客户端 服务器
配置位置 客户端 服务器端
隐藏对象 客户端IP 服务器IP
典型应用 翻墙、访问控制 负载均衡、安全防护
配置复杂度 简单 复杂
性能要求 一般

1.3 Nginx代理模块介绍

Nginx提供了多个代理相关的模块:

核心代理模块:

  • ngx_http_proxy_module:HTTP反向代理模块
  • ngx_http_upstream_module:上游服务器定义模块
  • ngx_stream_proxy_module:TCP/UDP代理模块

功能增强模块:

  • ngx_http_proxy_connect_module:HTTPS正向代理支持
  • ngx_http_headers_module:HTTP头部处理模块
  • ngx_http_cache_module:缓存模块
  • ngx_http_ssl_module:SSL支持模块

二、正向代理配置详解

2.1 HTTP正向代理配置

基础HTTP正向代理

配置文件:/usr/local/nginx/conf/conf.d/forward-proxy.conf

# =============================================
# HTTP正向代理配置
# 监听端口:3128
# =============================================

server {
    # 监听代理端口
    listen 3128;
    
    # 服务器名称(可选)
    server_name proxy.example.com;
    
    # 解析器配置(DNS服务器)
    resolver 8.8.8.8 8.8.4.4 114.114.114.114;
    
    # 解析器超时时间
    resolver_timeout 30s;
    
    # 访问日志
    access_log /var/log/nginx/proxy.access.log main;
    
    # 错误日志
    error_log /var/log/nginx/proxy.error.log warn;
    
    # =============================================
    # 正向代理配置
    # =============================================
    
    location / {
        # 代理目标地址
        # $http_host: 请求的主机名
        # $request_uri: 请求的URI
        proxy_pass http://$http_host$request_uri;
        
        # 设置代理头信息
        proxy_set_header Host $http_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 30s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # 代理缓冲区设置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
        proxy_busy_buffers_size 8k;
        
        # 代理临时文件路径
        proxy_temp_path /usr/local/nginx/proxy_temp;
        
        # 代理缓存路径
        proxy_cache_path /usr/local/nginx/proxy_cache levels=1:2 keys_zone=proxy_cache:10m inactive=60m use_temp_path=off;
        
        # 启用代理缓存
        proxy_cache proxy_cache;
        
        # 缓存有效期
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        
        # 缓存键
        proxy_cache_key $scheme$proxy_host$request_uri;
        
        # 缓存状态头
        add_header X-Proxy-Cache $upstream_cache_status;
    }
    
    # =============================================
    # 访问控制配置
    # =============================================
    
    # 限制访问IP(可选)
    allow 192.168.1.0/24;
    allow 10.0.0.0/8;
    deny all;
    
    # =============================================
    # 错误处理
    # =============================================
    
    # 代理连接错误处理
    error_page 502 503 504 /proxy_error.html;
    
    location = /proxy_error.html {
        root /usr/local/nginx/html;
        internal;
    }
}
带认证的HTTP正向代理
# =============================================
# 带认证的HTTP正向代理配置
# =============================================

server {
    listen 3128;
    server_name proxy.example.com;
    resolver 8.8.8.8 8.8.4.4;
    
    access_log /var/log/nginx/proxy.auth.access.log main;
    error_log /var/local/nginx/proxy.auth.error.log warn;
    
    # =============================================
    # 基本认证配置
    # =============================================
    
    # 启用HTTP基本认证
    auth_basic "Proxy Authentication";
    auth_basic_user_file /usr/local/nginx/conf/htpasswd.proxy;
    
    # =============================================
    # 代理配置
    # =============================================
    
    location / {
        # 检查认证状态
        if ($remote_user = "") {
            return 401;
        }
        
        # 代理目标地址
        proxy_pass http://$http_host$request_uri;
        
        # 设置代理头信息
        proxy_set_header Host $http_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_set_header X-Proxy-User $remote_user;
        
        # 代理超时设置
        proxy_connect_timeout 30s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # 代理缓冲区设置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
        proxy_busy_buffers_size 8k;
        
        # 代理缓存配置
        proxy_cache_path /usr/local/nginx/proxy_cache levels=1:2 keys_zone=proxy_cache:10m inactive=60m;
        proxy_cache proxy_cache;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        proxy_cache_key $scheme$proxy_host$request_uri;
        
        # 缓存状态头
        add_header X-Proxy-Cache $upstream_cache_status;
        
        # 访问日志记录用户
        access_log /var/log/nginx/proxy.auth.access.log main proxy=$upstream_addr user=$remote_user;
    }
    
    # =============================================
    # 访问控制
    # =============================================
    
    # 允许特定网段访问
    allow 192.168.1.0/24;
    allow 10.0.0.0/8;
    deny all;
}

2.2 HTTPS正向代理配置

基础HTTPS正向代理

配置文件:/usr/local/nginx/conf/conf.d/forward-proxy-https.conf

# =============================================
# HTTPS正向代理配置
# 监听端口:3129
# 注意:需要ngx_http_proxy_connect_module模块支持
# =============================================

server {
    # 监听HTTPS代理端口
    listen 3129;
    
    # 服务器名称
    server_name proxy.example.com;
    
    # DNS解析器
    resolver 8.8.8.8 8.8.4.4 114.114.114.114;
    resolver_timeout 30s;
    
    # 访问日志
    access_log /var/log/nginx/proxy.https.access.log main;
    
    # 错误日志
    error_log /var/log/nginx/proxy.https.error.log warn;
    
    # =============================================
    # HTTPS代理配置
    # =============================================
    
    location / {
        # HTTPS代理需要特殊处理
        proxy_pass https://$http_host$request_uri;
        
        # SSL相关配置
        proxy_ssl_server_name on;
        proxy_ssl_protocols TLSv1.2 TLSv1.3;
        proxy_ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
        proxy_ssl_session_reuse on;
        proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
        
        # 设置代理头信息
        proxy_set_header Host $http_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 30s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # SSL连接超时
        proxy_ssl_timeout 60s;
        
        # 代理缓冲区设置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
        proxy_busy_buffers_size 8k;
        
        # 代理临时文件路径
        proxy_temp_path /usr/local/nginx/proxy_temp;
        
        # 禁用缓存(HTTPS通常不缓存)
        proxy_cache off;
        
        # 添加SSL信息到日志
        add_header X-Proxy-SSL $proxy_ssl_server_name;
    }
    
    # =============================================
    # CONNECT方法处理(HTTPS握手)
    # =============================================
    
    # 处理CONNECT方法(用于HTTPS握手)
    location /connect {
        # 启用CONNECT方法支持
        proxy_connect_address $http_host:443;
        proxy_connect_connect_timeout 30s;
        proxy_connect_read_timeout 60s;
        proxy_connect_send_timeout 60s;
        
        # SSL配置
        proxy_ssl_server_name on;
        proxy_ssl_protocols TLSv1.2 TLSv1.3;
        proxy_ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
        
        # 代理头信息
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        
        # 超时设置
        proxy_connect_timeout 30s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
    
    # =============================================
    # 访问控制
    # =============================================
    
    # 限制访问IP
    allow 192.168.1.0/24;
    allow 10.0.0.0/8;
    deny all;
    
    # =============================================
    # 错误处理
    # =============================================
    
    # SSL连接错误处理
    error_page 497 495 496 /proxy_ssl_error.html;
    
    location = /proxy_ssl_error.html {
        root /usr/local/nginx/html;
        internal;
    }
    
    # 代理连接错误处理
    error_page 502 503 504 /proxy_error.html;
    
    location = /proxy_error.html {
        root /usr/local/nginx/html;
        internal;
    }
}
带缓存的HTTPS正向代理
# =============================================
# 带缓存的HTTPS正向代理配置
# =============================================

server {
    listen 3129;
    server_name proxy.example.com;
    resolver 8.8.8.8 8.8.4.4;
    resolver_timeout 30s;
    
    access_log /var/log/nginx/proxy.https.cache.access.log main;
    error_log /var/log/nginx/proxy.https.cache.error.log warn;
    
    # =============================================
    # 缓存配置
    # =============================================
    
    # HTTPS代理缓存路径
    proxy_cache_path /usr/local/nginx/proxy_https_cache levels=1:2 keys_zone=proxy_https_cache:20m inactive=120m use_temp_path=off;
    
    # =============================================
    # 代理配置
    # =============================================
    
    location / {
        # HTTPS代理
        proxy_pass https://$http_host$request_uri;
        
        # SSL配置
        proxy_ssl_server_name on;
        proxy_ssl_protocols TLSv1.2 TLSv1.3;
        proxy_ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
        proxy_ssl_session_reuse on;
        proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
        
        # 代理头信息
        proxy_set_header Host $http_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 30s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        proxy_ssl_timeout 60s;
        
        # 缓冲区设置
        proxy_buffering on;
        proxy_buffer_size 8k;
        proxy_buffers 8 8k;
        proxy_busy_buffers_size 16k;
        
        # 启用缓存
        proxy_cache proxy_https_cache;
        
        # 缓存条件:只缓存成功的响应
        proxy_cache_valid 200 302 30m;
        proxy_cache_valid 301 1h;
        proxy_cache_valid 404 1m;
        proxy_cache_valid 500 502 503 504 0s;
        
        # 缓存键
        proxy_cache_key $scheme$proxy_host$request_uri;
        
        # 缓存控制
        proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
        proxy_cache_lock on;
        proxy_cache_lock_timeout 5s;
        
        # 缓存状态头
        add_header X-Proxy-Cache $upstream_cache_status;
        
        # 绕过缓存的条件
        proxy_cache_bypass $cookie_nocache $arg_nocache $arg_comment;
        proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
    }
    
    # =============================================
    # 特殊资源缓存配置
    # =============================================
    
    # 静态资源缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|eot)$ {
        proxy_pass https://$http_host$request_uri;
        
        # SSL配置
        proxy_ssl_server_name on;
        proxy_ssl_protocols TLSv1.2 TLSv1.3;
        
        # 代理头信息
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        
        # 静态资源缓存时间更长
        proxy_cache proxy_https_cache;
        proxy_cache_valid 200 302 24h;
        proxy_cache_valid 404 1m;
        proxy_cache_key $scheme$proxy_host$request_uri;
        
        # 缓存状态头
        add_header X-Proxy-Cache $upstream_cache_status;
        
        # 浏览器缓存控制
        add_header Cache-Control "public, max-age=86400";
        
        # 关闭访问日志
        access_log off;
    }
    
    # =============================================
    # 访问控制
    # =============================================
    
    allow 192.168.1.0/24;
    allow 10.0.0.0/8;
    deny all;
}

2.3 正向代理客户端配置

Windows客户端配置

Internet Explorer/Edge:

  1. 打开IE设置 → Internet选项
  2. 选择"连接"选项卡
  3. 点击"局域网设置"
  4. 勾选"为LAN使用代理服务器"
  5. 输入代理服务器地址和端口
  6. 点击"确定"保存

Chrome浏览器:

  1. 打开设置 → 高级 → 系统
  2. 点击"打开您计算机的代理设置"
  3. 配置代理服务器地址和端口

Firefox浏览器:

  1. 打开设置 → 常规 → 网络设置
  2. 选择"手动代理配置"
  3. 输入HTTP代理和HTTPS代理
  4. 勾选"同时用于HTTPS"
Linux客户端配置

环境变量方式:

# 设置HTTP代理
export http_proxy="http://proxy.example.com:3128"
export https_proxy="http://proxy.example.com:3129"

# 设置FTP代理
export ftp_proxy="http://proxy.example.com:3128"

# 设置不使用代理的地址
export no_proxy="localhost,127.0.0.1,*.local"

# 永久生效(添加到~/.bashrc或/etc/profile)
echo 'export http_proxy="http://proxy.example.com:3128"' >> ~/.bashrc
echo 'export https_proxy="http://proxy.example.com:3129"' >> ~/.bashrc
source ~/.bashrc

APT/YUM包管理器配置:

# APT代理配置(Ubuntu/Debian)
cat > /etc/apt/apt.conf.d/01proxy << EOF
Acquire::http::Proxy "http://proxy.example.com:3128";
Acquire::https::Proxy "http://proxy.example.com:3129";
EOF

# YUM代理配置(CentOS/RHEL)
cat > /etc/yum.conf << EOF
[main]
proxy=http://proxy.example.com:3128
EOF
macOS客户端配置

系统代理设置:

  1. 打开系统偏好设置 → 网络
  2. 选择当前网络连接 → 高级
  3. 选择"代理"选项卡
  4. 配置HTTP和HTTPS代理
  5. 点击"确定"保存

命令行配置:

# 设置网络代理
networksetup -setwebproxy Wi-Fi proxy.example.com 3128
networksetup -setsecurewebproxy Wi-Fi proxy.example.com 3129

# 设置代理认证
networksetup -setwebproxy Wi-Fi proxy.example.com 3128 on username password
networksetup -setsecurewebproxy Wi-Fi proxy.example.com 3129 on username password

三、反向代理配置详解

3.1 基础反向代理配置

单后端服务器反向代理

配置文件:/usr/local/nginx/conf/conf.d/reverse-proxy-basic.conf

# =============================================
# 基础反向代理配置
# 监听端口:80
# 后端服务器:127.0.0.1:8080
# =============================================

server {
    # 监听端口
    listen 80;
    
    # 服务器名称
    server_name web.example.com;
    
    # 网站根目录(可选)
    root /usr/local/nginx/html/web.example.com;
    
    # 默认首页文件
    index index.html index.htm;
    
    # 字符集设置
    charset utf-8;
    
    # 访问日志
    access_log /var/log/nginx/web.example.com.access.log main;
    
    # 错误日志
    error_log /var/log/nginx/web.example.com.error.log warn;
    
    # =============================================
    # 反向代理配置
    # =============================================
    
    location / {
        # 后端服务器地址
        proxy_pass http://127.0.0.1:8080;
        
        # 设置代理头信息
        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_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Port $server_port;
        
        # 连接超时设置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # 代理缓冲区设置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
        proxy_busy_buffers_size 8k;
        
        # 代理临时文件路径
        proxy_temp_path /usr/local/nginx/proxy_temp;
        
        # 代理重定向设置
        proxy_redirect off;
        
        # Cookie设置
        proxy_cookie_domain off;
        proxy_cookie_path off;
        
        # HTTP版本设置
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        
        # 客户端请求体大小
        client_max_body_size 50m;
        client_body_buffer_size 128k;
    }
    
    # =============================================
    # 静态文件处理
    # =============================================
    
    # 静态文件直接由Nginx处理
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|eot|svg)$ {
        # 尝试访问本地文件
        try_files $uri =404;
        
        # 设置缓存头
        expires 7d;
        add_header Cache-Control "public, no-transform";
        
        # 关闭访问日志
        access_log off;
    }
    
    # =============================================
    # 健康检查
    # =============================================
    
    # 健康检查端点
    location /health {
        access_log off;
        return 200 "healthy\n";
        add_header Content-Type text/plain;
    }
    
    # =============================================
    # 错误处理
    # =============================================
    
    # 错误页面
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    
    location = /50x.html {
        root /usr/local/nginx/html;
    }
}
多后端服务器反向代理

配置文件:/usr/local/nginx/conf/conf.d/reverse-proxy-multiple.conf

# =============================================
# 多后端服务器反向代理配置
# 监听端口:80
# 后端服务器组:backend_servers
# =============================================

# 定义后端服务器组
upstream backend_servers {
    # 后端服务器列表
    server 192.168.1.10:8080 weight=5 max_fails=3 fail_timeout=30s;
    server 192.168.1.11:8080 weight=3 max_fails=3 fail_timeout=30s;
    server 192.168.1.12:8080 weight=2 max_fails=3 fail_timeout=30s backup;
    
    # 负载均衡方法
    # least_conn;  # 最少连接
    # ip_hash;     # IP哈希
    
    # 保持连接设置
    keepalive 32;
    keepalive_timeout 30s;
    keepalive_requests 1000;
}

server {
    listen 80;
    server_name api.example.com;
    
    access_log /var/log/nginx/api.example.com.access.log main;
    error_log /var/log/nginx/api.example.com.error.log warn;
    
    # =============================================
    # 反向代理配置
    # =============================================
    
    location / {
        # 代理到后端服务器组
        proxy_pass http://backend_servers;
        
        # 代理头信息
        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_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Port $server_port;
        
        # 连接设置
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        
        # 超时设置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # 缓冲区设置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
        proxy_busy_buffers_size 8k;
        
        # 重定向设置
        proxy_redirect off;
        
        # Cookie设置
        proxy_cookie_domain off;
        proxy_cookie_path off;
        
        # 请求体大小
        client_max_body_size 100m;
        client_body_buffer_size 128k;
        
        # 代理缓存配置
        proxy_cache_path /usr/local/nginx/proxy_cache levels=1:2 keys_zone=api_cache:10m inactive=60m;
        proxy_cache api_cache;
        proxy_cache_valid 200 302 5m;
        proxy_cache_valid 404 1m;
        proxy_cache_key $scheme$request_method$host$request_uri;
        
        # 缓存控制
        proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
        proxy_cache_lock on;
        proxy_cache_lock_timeout 5s;
        
        # 缓存状态头
        add_header X-Proxy-Cache $upstream_cache_status;
        
        # 绕过缓存
        proxy_cache_bypass $cookie_nocache $arg_nocache $arg_comment;
        proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
    }
    
    # =============================================
    # API路径配置
    # =============================================
    
    # API v1路径
    location /api/v1/ {
        proxy_pass http://backend_servers;
        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;
        
        # API特定设置
        proxy_connect_timeout 30s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
        
        # API缓存
        proxy_cache api_cache;
        proxy_cache_valid 200 302 1m;
        proxy_cache_key $scheme$request_method$host$request_uri;
        
        # CORS设置
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
        
        # 处理OPTIONS请求
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain; charset=utf-8';
            add_header 'Content-Length' 0;
            return 204;
        }
    }
    
    # =============================================
    # 静态资源
    # =============================================
    
    location ~* \.(css|js|jpg|jpeg|png|gif|ico|woff|woff2|ttf|eot|svg)$ {
        # 尝试本地文件
        try_files $uri =404;
        
        # 缓存设置
        expires 30d;
        add_header Cache-Control "public, no-transform";
        
        # 关闭日志
        access_log off;
    }
    
    # =============================================
    # 健康检查
    # =============================================
    
    location /health {
        access_log off;
        proxy_pass http://backend_servers/health;
        proxy_connect_timeout 5s;
        proxy_read_timeout 5s;
    }
}

3.2 带负载均衡的反向代理

轮询负载均衡
# =============================================
# 轮询负载均衡配置
# =============================================

# 定义后端服务器组(轮询方式)
upstream backend_round_robin {
    # 轮询方式(默认)
    server 192.168.1.10:8080;
    server 192.168.1.11:8080;
    server 192.168.1.12:8080;
    
    # 连接保持设置
    keepalive 32;
    keepalive_timeout 30s;
    keepalive_requests 1000;
}

server {
    listen 80;
    server_name lb.example.com;
    
    access_log /var/log/nginx/lb.example.com.access.log main;
    error_log /var/log/nginx/lb.example.com.error.log warn;
    
    location / {
        proxy_pass http://backend_round_robin;
        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_http_version 1.1;
        proxy_set_header Connection "";
        
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
        proxy_busy_buffers_size 8k;
    }
}
加权轮询负载均衡
# =============================================
# 加权轮询负载均衡配置
# =============================================

# 定义后端服务器组(加权轮询)
upstream backend_weighted {
    # 权重分配,数值越大分配到的请求越多
    server 192.168.1.10:8080 weight=5;    # 50%的请求
    server 192.168.1.11:8080 weight=3;    # 30%的请求
    server 192.168.1.12:8080 weight=2;    # 20%的请求
    
    # 健康检查设置
    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 max_fails=3 fail_timeout=30s;
    
    # 连接保持
    keepalive 32;
    keepalive_timeout 30s;
    keepalive_requests 1000;
}

server {
    listen 80;
    server_name weighted.example.com;
    
    access_log /var/log/nginx/weighted.example.com.access.log main;
    error_log /var/log/nginx/weighted.example.com.error.log warn;
    
    location / {
        proxy_pass http://backend_weighted;
        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_http_version 1.1;
        proxy_set_header Connection "";
        
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # 添加负载均衡信息到日志
        add_header X-Upstream-Addr $upstream_addr;
        add_header X-Upstream-Response-Time $upstream_response_time;
    }
}
IP哈希负载均衡
# =============================================
# IP哈希负载均衡配置
# =============================================

# 定义后端服务器组(IP哈希)
upstream backend_ip_hash {
    # IP哈希方式,确保同一客户端请求始终转发到同一服务器
    ip_hash;
    
    server 192.168.1.10:8080;
    server 192.168.1.11:8080;
    server 192.168.1.12:8080;
    
    # 健康检查
    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 max_fails=3 fail_timeout=30s;
    
    # 连接保持
    keepalive 32;
    keepalive_timeout 30s;
    keepalive_requests 1000;
}

server {
    listen 80;
    server_name iphash.example.com;
    
    access_log /var/log/nginx/iphash.example.com.access.log main;
    error_log /var/log/nginx/iphash.example.com.error.log warn;
    
    location / {
        proxy_pass http://backend_ip_hash;
        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_http_version 1.1;
        proxy_set_header Connection "";
        
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # 添加客户端哈希信息
        add_header X-Client-Hash $remote_addr;
        add_header X-Upstream-Addr $upstream_addr;
    }
}
最少连接负载均衡
# =============================================
# 最少连接负载均衡配置
# =============================================

# 定义后端服务器组(最少连接)
upstream backend_least_conn {
    # 最少连接方式,将请求转发到连接数最少的服务器
    least_conn;
    
    server 192.168.1.10:8080;
    server 192.168.1.11:8080;
    server 192.168.1.12:8080;
    
    # 健康检查
    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 max_fails=3 fail_timeout=30s;
    
    # 连接保持
    keepalive 32;
    keepalive_timeout 30s;
    keepalive_requests 1000;
}

server {
    listen 80;
    server_name leastconn.example.com;
    
    access_log /var/log/nginx/leastconn.example.com.access.log main;
    error_log /var/log/nginx/leastconn.example.com.error.log warn;
    
    location / {
        proxy_pass http://backend_least_conn;
        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_http_version 1.1;
        proxy_set_header Connection "";
        
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # 添加连接数信息
        add_header X-Upstream-Addr $upstream_addr;
        add_header X-Upstream-Connections $upstream_connections;
    }
}

3.3 带缓存的反向代理

基础缓存配置
# =============================================
# 带缓存的反向代理配置
# =============================================

# 定义缓存路径和参数
proxy_cache_path /usr/local/nginx/proxy_cache levels=1:2 keys_zone=cache_zone:10m inactive=60m use_temp_path=off;
proxy_cache_path /usr/local/nginx/proxy_cache_api levels=1:2 keys_zone=api_cache:20m inactive=120m use_temp_path=off;

server {
    listen 80;
    server_name cache.example.com;
    
    access_log /var/log/nginx/cache.example.com.access.log main;
    error_log /var/log/nginx/cache.example.com.error.log warn;
    
    # =============================================
    # 基础缓存配置
    # =============================================
    
    location / {
        # 后端服务器
        proxy_pass http://127.0.0.1:8080;
        
        # 代理头信息
        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_cache cache_zone;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 301 1h;
        proxy_cache_valid 404 1m;
        proxy_cache_valid 500 502 503 504 0s;
        
        # 缓存键
        proxy_cache_key $scheme$request_method$host$request_uri;
        
        # 缓存控制
        proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
        proxy_cache_lock on;
        proxy_cache_lock_timeout 5s;
        
        # 缓存状态头
        add_header X-Proxy-Cache $upstream_cache_status;
        
        # 绕过缓存
        proxy_cache_bypass $cookie_nocache $arg_nocache $arg_comment;
        proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
    }
    
    # =============================================
    # API缓存配置
    # =============================================
    
    location /api/ {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        
        # API专用缓存
        proxy_cache api_cache;
        proxy_cache_valid 200 302 5m;
        proxy_cache_valid 404 1m;
        proxy_cache_key $scheme$request_method$host$request_uri;
        
        # API缓存控制
        proxy_cache_use_stale error timeout updating;
        proxy_cache_lock on;
        proxy_cache_lock_timeout 3s;
        
        # CORS设置
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
        
        # 缓存状态头
        add_header X-Proxy-Cache $upstream_cache_status;
    }
    
    # =============================================
    # 静态资源缓存
    # =============================================
    
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|eot|svg)$ {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        
        # 静态资源缓存
        proxy_cache cache_zone;
        proxy_cache_valid 200 302 24h;
        proxy_cache_valid 404 1m;
        proxy_cache_key $scheme$request_method$host$request_uri;
        
        # 浏览器缓存控制
        expires 30d;
        add_header Cache-Control "public, no-transform";
        
        # 缓存状态头
        add_header X-Proxy-Cache $upstream_cache_status;
        
        # 关闭访问日志
        access_log off;
    }
    
    # =============================================
    # 缓存清理接口
    # =============================================
    
    location /purge/ {
        # 限制访问IP
        allow 127.0.0.1;
        allow 192.168.1.0/24;
        deny all;
        
        # 缓存清理
        proxy_cache_purge cache_zone $scheme$request_method$host$request_uri;
        proxy_cache_purge api_cache $scheme$request_method$host$request_uri;
        
        # 返回清理结果
        add_header Content-Type "text/plain";
        return 200 "Cache purged\n";
    }
}
高级缓存配置
# =============================================
# 高级缓存配置
# =============================================

# 定义多个缓存区域
proxy_cache_path /usr/local/nginx/proxy_cache_static levels=1:2 keys_zone=static_cache:50m inactive=24h use_temp_path=off;
proxy_cache_path /usr/local/nginx/proxy_cache_api levels=1:2 keys_zone=api_cache:100m inactive=2h use_temp_path=off;
proxy_cache_path /usr/local/nginx/proxy_cache_dynamic levels=1:2 keys_zone=dynamic_cache:200m inactive=1h use_temp_path=off;

server {
    listen 80;
    server_name advanced-cache.example.com;
    
    access_log /var/log/nginx/advanced-cache.example.com.access.log main;
    error_log /var/log/nginx/advanced-cache.example.com.error.log warn;
    
    # =============================================
    # 缓存条件变量
    # =============================================
    
    # 定义缓存条件变量
    map $request_method $no_cache_method {
        POST 1;
        PUT 1;
        DELETE 1;
        PATCH 1;
        default 0;
    }
    
    map $cookie_user_token $no_cache_auth {
        default 0;
        "~*" 1;
    }
    
    map $arg_nocache $no_cache_arg {
        default 0;
        "1" 1;
        "true" 1;
    }
    
    # =============================================
    # 静态资源缓存
    # =============================================
    
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|eot|svg)$ {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        
        # 静态资源缓存
        proxy_cache static_cache;
        proxy_cache_valid 200 302 7d;
        proxy_cache_valid 404 1h;
        proxy_cache_key $scheme$request_method$host$request_uri;
        
        # 缓存控制
        proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
        proxy_cache_lock on;
        proxy_cache_lock_timeout 5s;
        
        # 浏览器缓存
        expires 30d;
        add_header Cache-Control "public, no-transform";
        
        # 缓存状态
        add_header X-Proxy-Cache $upstream_cache_status;
        
        # 关闭日志
        access_log off;
    }
    
    # =============================================
    # API缓存
    # =============================================
    
    location /api/ {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        
        # API缓存
        proxy_cache api_cache;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        proxy_cache_key $scheme$request_method$host$request_uri;
        
        # 缓存控制
        proxy_cache_use_stale error timeout updating;
        proxy_cache_lock on;
        proxy_cache_lock_timeout 3s;
        
        # 条件缓存
        proxy_no_cache $no_cache_method $no_cache_auth $no_cache_arg;
        proxy_cache_bypass $no_cache_method $no_cache_auth $no_cache_arg;
        
        # CORS
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
        
        # 缓存状态
        add_header X-Proxy-Cache $upstream_cache_status;
        add_header X-Cache-Condition "method=$no_cache_method,auth=$no_cache_auth,arg=$no_cache_arg";
    }
    
    # =============================================
    # 动态内容缓存
    # =============================================
    
    location /dynamic/ {
        proxy_pass http://127.0.0.1:8080;
        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_cache dynamic_cache;
        proxy_cache_valid 200 302 1m;
        proxy_cache_valid 404 30s;
        proxy_cache_key $scheme$request_method$host$request_uri;
        
        # 缓存控制
        proxy_cache_use_stale error timeout updating;
        proxy_cache_lock on;
        proxy_cache_lock_timeout 2s;
        
        # 条件缓存(更严格)
        proxy_no_cache $no_cache_method $no_cache_auth $no_cache_arg;
        proxy_cache_bypass $no_cache_method $no_cache_auth $no_cache_arg;
        
        # 缓存状态
        add_header X-Proxy-Cache $upstream_cache_status;
    }
    
    # =============================================
    # 缓存统计接口
    # =============================================
    
    location /cache_status/ {
        # 限制访问
        allow 127.0.0.1;
        allow 192.168.1.0/24;
        deny all;
        
        # 返回缓存统计信息
        add_header Content-Type "application/json";
        return 200 '{
            "static_cache": {
                "size": "50MB",
                "inactive": "24h"
            },
            "api_cache": {
                "size": "100MB",
                "inactive": "2h"
            },
            "dynamic_cache": {
                "size": "200MB",
                "inactive": "1h"
            }
        }';
    }
    
    # =============================================
    # 缓存清理接口
    # =============================================
    
    location /purge/ {
        # 限制访问
        allow 127.0.0.1;
        allow 192.168.1.0/24;
        deny all;
        
        # 根据URL清理缓存
        location ~ ^/purge/static/(.*)$ {
            proxy_cache_purge static_cache $scheme$request_method$host/$1;
        }
        
        location ~ ^/purge/api/(.*)$ {
            proxy_cache_purge api_cache $scheme$request_method$host/$1;
        }
        
        location ~ ^/purge/dynamic/(.*)$ {
            proxy_cache_purge dynamic_cache $scheme$request_method$host/$1;
        }
        
        # 返回清理结果
        add_header Content-Type "text/plain";
        return 200 "Cache purged\n";
    }
}

四、代理配置高级应用

4.1 SSL/TLS终止

HTTPS反向代理配置
# =============================================
# HTTPS反向代理配置(SSL终止)
# =============================================

server {
    # 监听443端口(HTTPS)
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    
    # 服务器名称
    server_name secure.example.com;
    
    # SSL证书配置
    ssl_certificate /usr/local/nginx/conf/ssl/secure.example.com.crt;
    ssl_certificate_key /usr/local/nginx/conf/ssl/secure.example.com.key;
    
    # SSL协议和加密套件
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384;
    ssl_prefer_server_ciphers on;
    
    # SSL会话配置
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_session_tickets on;
    
    # OCSP装订
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_trusted_certificate /usr/local/nginx/conf/ssl/chain.pem;
    
    # HSTS
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
    
    access_log /var/log/nginx/secure.example.com.access.log main;
    error_log /var/log/nginx/secure.example.com.error.log warn;
    
    # =============================================
    # 反向代理配置
    # =============================================
    
    location / {
        # 后端服务器(HTTP)
        proxy_pass http://127.0.0.1:8080;
        
        # 代理头信息
        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_set_header X-Forwarded-SSL $ssl_protocol;
        proxy_set_header X-Forwarded-SSL-Cipher $ssl_cipher;
        
        # 连接设置
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        
        # 超时设置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # 缓冲区设置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
        proxy_busy_buffers_size 8k;
        
        # 设置HTTPS参数
        proxy_set_header HTTPS on;
        proxy_set_header HTTP_SCHEME https;
    }
    
    # =============================================
    # WebSocket代理
    # =============================================
    
    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_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;
        
        # WebSocket超时设置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}

# =============================================
# HTTP重定向到HTTPS
# =============================================

server {
    listen 80;
    listen [::]:80;
    server_name secure.example.com;
    
    # 重定向到HTTPS
    return 301 https://$server_name$request_uri;
}

4.2 WebSocket代理

# =============================================
# WebSocket代理配置
# =============================================

server {
    listen 80;
    server_name ws.example.com;
    
    access_log /var/log/nginx/ws.example.com.access.log main;
    error_log /var/log/nginx/ws.example.com.error.log warn;
    
    # =============================================
    # WebSocket代理配置
    # =============================================
    
    location /ws/ {
        # WebSocket后端服务器
        proxy_pass http://127.0.0.1:8080;
        
        # WebSocket必要头信息
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        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;
        
        # WebSocket超时设置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # 缓冲区设置(WebSocket通常不缓冲)
        proxy_buffering off;
        
        # 心跳设置
        proxy_set_header Connection "";
    }
    
    # =============================================
    # 带认证的WebSocket
    # =============================================
    
    location /ws-auth/ {
        # 基本认证
        auth_basic "WebSocket Authentication";
        auth_basic_user_file /usr/local/nginx/conf/htpasswd.ws;
        
        # WebSocket代理
        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_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_set_header X-WS-User $remote_user;
        
        # 超时设置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        proxy_buffering off;
    }
    
    # =============================================
    # WebSocket负载均衡
    # =============================================
    
    location /ws-lb/ {
        # 定义WebSocket后端服务器组
        proxy_pass http://websocket_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        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 off;
    }
}

# =============================================
# WebSocket后端服务器组
# =============================================

upstream websocket_backend {
    # IP哈希确保同一客户端连接到同一服务器
    ip_hash;
    
    server 192.168.1.10:8080;
    server 192.168.1.11:8080;
    server 192.168.1.12:8080;
    
    # 健康检查
    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 max_fails=3 fail_timeout=30s;
    
    # 连接保持
    keepalive 32;
    keepalive_timeout 30s;
    keepalive_requests 1000;
}

4.3 代理健康检查

被动健康检查
# =============================================
# 被动健康检查配置
# =============================================

upstream backend_health_check {
    # 后端服务器配置
    server 192.168.1.10:8080 weight=5 max_fails=3 fail_timeout=30s;
    server 192.168.1.11:8080 weight=3 max_fails=3 fail_timeout=30s;
    server 192.168.1.12:8080 weight=2 max_fails=3 fail_timeout=30s backup;
    
    # 负载均衡方法
    least_conn;
    
    # 连接保持
    keepalive 32;
    keepalive_timeout 30s;
    keepalive_requests 1000;
}

server {
    listen 80;
    server_name health.example.com;
    
    access_log /var/log/nginx/health.example.com.access.log main;
    error_log /var/log/nginx/health.example.com.error.log warn;
    
    location / {
        proxy_pass http://backend_health_check;
        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_http_version 1.1;
        proxy_set_header Connection "";
        
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # 添加健康检查信息
        add_header X-Upstream-Status $upstream_status;
        add_header X-Upstream-Response-Time $upstream_response_time;
        add_header X-Upstream-Addr $upstream_addr;
    }
    
    # =============================================
    # 健康检查端点
    # =============================================
    
    location /health {
        # 限制访问
        allow 127.0.0.1;
        allow 192.168.1.0/24;
        deny all;
        
        # 返回健康状态
        add_header Content-Type "application/json";
        return 200 '{
            "status": "healthy",
            "upstream": "backend_health_check",
            "servers": [
                {"addr": "192.168.1.10:8080", "status": "up"},
                {"addr": "192.168.1.11:8080", "status": "up"},
                {"addr": "192.168.1.12:8080", "status": "backup"}
            ]
        }';
    }
}
主动健康检查(需要nginx_plus或第三方模块)
# =============================================
# 主动健康检查配置(需要nginx_plus)
# =============================================

upstream backend_active_health {
    zone backend_active_health 64k;
    
    server 192.168.1.10:8080 slow_start=30s;
    server 192.168.1.11:8080 slow_start=30s;
    server 192.168.1.12:8080 slow_start=30s backup;
    
    # 主动健康检查
    health_check interval=10s fails=3 passes=2 uri=/health port=8080;
    
    # 负载均衡
    least_conn;
    
    # 连接保持
    keepalive 32;
    keepalive_timeout 30s;
    keepalive_requests 1000;
}

server {
    listen 80;
    server_name active-health.example.com;
    
    access_log /var/log/nginx/active-health.example.com.access.log main;
    error_log /var/log/nginx/active-health.example.com.error.log warn;
    
    location / {
        proxy_pass http://backend_active_health;
        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_http_version 1.1;
        proxy_set_header Connection "";
        
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # 添加健康状态信息
        add_header X-Upstream-Status $upstream_status;
        add_header X-Upstream-Response-Time $upstream_response_time;
        add_header X-Upstream-Addr $upstream_addr;
    }
    
    # =============================================
    # 健康状态监控
    # =============================================
    
    location /upstream_status {
        # 限制访问
        allow 127.0.0.1;
        allow 192.168.1.0/24;
        deny all;
        
        # 显示上游服务器状态
        upstream_status;
        
        add_header Content-Type "text/plain";
    }
}

五、代理配置常见问题与解决方案

5.1 代理连接超时

问题现象:

2024/01/15 10:30:15 [error] 12345#0: *12345 upstream timed out (110: Connection timed out) while connecting to upstream

解决方案:

# 调整代理超时设置
location / {
    proxy_pass http://backend;
    proxy_set_header Host $host;
    
    # 增加连接超时时间
    proxy_connect_timeout 120s;
    proxy_send_timeout 120s;
    proxy_read_timeout 120s;
    
    # 启用代理缓冲
    proxy_buffering on;
    proxy_buffer_size 8k;
    proxy_buffers 8 8k;
    proxy_busy_buffers_size 16k;
}

5.2 代理缓存问题

问题现象:

  • 缓存不生效
  • 缓存内容过期
  • 缓存清理失败

解决方案:

# 检查缓存配置
proxy_cache_path /usr/local/nginx/proxy_cache levels=1:2 keys_zone=cache_zone:10m inactive=60m;

location / {
    proxy_pass http://backend;
    proxy_set_header Host $host;
    
    # 确保缓存启用
    proxy_cache cache_zone;
    proxy_cache_valid 200 302 10m;
    proxy_cache_key $scheme$request_method$host$request_uri;
    
    # 添加缓存状态头
    add_header X-Proxy-Cache $upstream_cache_status;
    
    # 检查缓存条件
    proxy_cache_bypass $cookie_nocache $arg_nocache;
    proxy_no_cache $cookie_nocache $arg_nocache;
}

5.3 SSL代理问题

问题现象:

2024/01/15 10:30:15 [error] 12345#0: *12345 SSL_do_handshake() failed (SSL: error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure)

解决方案:

# 调整SSL配置
location / {
    proxy_pass https://backend;
    proxy_set_header Host $host;
    
    # SSL配置
    proxy_ssl_server_name on;
    proxy_ssl_protocols TLSv1.2 TLSv1.3;
    proxy_ssl_ciphers HIGH:!aNULL:!MD5;
    proxy_ssl_session_reuse on;
    proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
    
    # SSL超时设置
    proxy_ssl_timeout 60s;
}

5.4 WebSocket代理问题

问题现象:

  • WebSocket连接失败
  • 连接频繁断开

解决方案:

# WebSocket代理配置
location /ws/ {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    proxy_set_header Host $host;
    
    # 禁用缓冲
    proxy_buffering off;
    
    # 调整超时时间
    proxy_connect_timeout 120s;
    proxy_send_timeout 120s;
    proxy_read_timeout 120s;
    
    # 心跳设置
    proxy_set_header Connection "";
}

性能优化建议:

  • 启用keepalive减少连接开销
  • 合理配置缓存策略
  • 使用负载均衡分散请求
  • 启用压缩减少传输数据量
  • 监控代理性能指标

安全配置建议:

  • 限制代理访问权限
  • 启用SSL/TLS加密
  • 配置适当的安全头
  • 定期更新SSL证书
  • 监控异常访问行为

Nginx代理功能是现代网络架构中不可或缺的组成部分。通过本文的学习,你应该能够熟练配置和管理Nginx代理服务器,为构建高性能、高可用的网络服务打下坚实基础。


网站公告

今日签到

点亮在社区的每一天
去签到