Nginx反向代理 #

一、反向代理概述 #

1.1 什么是反向代理 #

反向代理(Reverse Proxy)是指以代理服务器来接受Internet上的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给Internet上请求连接的客户端。

text
客户端 → 反向代理服务器 → 后端服务器
         (Nginx)         (应用服务器)

1.2 正向代理 vs 反向代理 #

特性 正向代理 反向代理
代理对象 客户端 服务器
用途 访问外网、隐藏客户端 负载均衡、隐藏服务器
典型应用 VPN、科学上网 Nginx、HAProxy

1.3 反向代理的优势 #

  • 负载均衡:分发请求到多台服务器
  • 安全性:隐藏后端服务器真实IP
  • 缓存:缓存后端响应,减轻服务器压力
  • SSL终结:集中处理HTTPS加密
  • 压缩:统一压缩响应内容

二、基本配置 #

2.1 最简反向代理 #

nginx
server {
    listen 80;
    server_name api.example.com;
    
    location / {
        proxy_pass http://192.168.1.100:8080;
    }
}

2.2 完整代理配置 #

nginx
server {
    listen 80;
    server_name api.example.com;
    
    location / {
        proxy_pass http://192.168.1.100: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_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
    }
}

2.3 proxy_pass规则 #

带URI的proxy_pass:

nginx
location /api/ {
    proxy_pass http://backend/;
}

请求 /api/users → 转发到 http://backend/users

不带URI的proxy_pass:

nginx
location /api/ {
    proxy_pass http://backend;
}

请求 /api/users → 转发到 http://backend/api/users

三、请求头传递 #

3.1 常用请求头 #

nginx
location / {
    proxy_pass http://backend;
    
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Port $server_port;
}

3.2 请求头说明 #

请求头 说明
Host 原始请求的主机名
X-Real-IP 客户端真实IP
X-Forwarded-For 代理链IP列表
X-Forwarded-Proto 原始协议(http/https)
X-Forwarded-Host 原始主机名
X-Forwarded-Port 原始端口

3.3 自定义请求头 #

nginx
location / {
    proxy_pass http://backend;
    proxy_set_header X-Request-ID $request_id;
    proxy_set_header X-Client-Cert $ssl_client_cert;
    proxy_set_header X-User-Agent $http_user_agent;
}

四、超时配置 #

4.1 超时参数 #

nginx
location / {
    proxy_pass http://backend;
    
    proxy_connect_timeout 60s;
    proxy_send_timeout 60s;
    proxy_read_timeout 60s;
    
    proxy_next_upstream_timeout 30s;
    proxy_next_upstream_tries 3;
}
参数 说明 默认值
proxy_connect_timeout 连接后端超时 60s
proxy_send_timeout 发送请求超时 60s
proxy_read_timeout 读取响应超时 60s
proxy_next_upstream_timeout 下一个服务器超时 0
proxy_next_upstream_tries 重试次数 0

4.2 长连接配置 #

nginx
location / {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
}

五、缓冲配置 #

5.1 开启缓冲 #

nginx
location / {
    proxy_pass http://backend;
    
    proxy_buffering on;
    proxy_buffer_size 4k;
    proxy_buffers 8 4k;
    proxy_busy_buffers_size 8k;
    proxy_temp_path /var/cache/nginx/proxy_temp;
    proxy_max_temp_file_size 1024m;
}

5.2 关闭缓冲 #

nginx
location /stream/ {
    proxy_pass http://backend;
    proxy_buffering off;
    proxy_cache off;
}

5.3 缓冲参数说明 #

参数 说明
proxy_buffering 是否开启缓冲
proxy_buffer_size 响应头缓冲区大小
proxy_buffers 响应体缓冲区数量和大小
proxy_busy_buffers_size 忙碌缓冲区大小

六、代理缓存 #

6.1 缓存配置 #

nginx
http {
    proxy_cache_path /var/cache/nginx/proxy 
                     levels=1:2 
                     keys_zone=proxy_cache:10m 
                     max_size=1g 
                     inactive=60m 
                     use_temp_path=off;
    
    server {
        location / {
            proxy_pass http://backend;
            proxy_cache proxy_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 http_500 http_502 http_503 http_504;
            add_header X-Cache-Status $upstream_cache_status;
        }
    }
}

6.2 缓存参数说明 #

参数 说明
levels 缓存目录层级
keys_zone 共享内存区域名称和大小
max_size 最大缓存大小
inactive 不活跃删除时间
proxy_cache_valid 响应状态码缓存时间
proxy_cache_key 缓存键
proxy_cache_use_stale 错误时使用过期缓存

6.3 缓存状态 #

状态 说明
HIT 缓存命中
MISS 缓存未命中
EXPIRED 缓存过期
STALE 使用过期缓存
UPDATING 缓存更新中
BYPASS 跳过缓存

6.4 不缓存特定请求 #

nginx
location / {
    proxy_pass http://backend;
    proxy_cache proxy_cache;
    
    proxy_cache_bypass $cookie_nocache $arg_nocache;
    proxy_no_cache $cookie_nocache $arg_nocache;
}

七、WebSocket代理 #

7.1 WebSocket配置 #

nginx
map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}

server {
    listen 80;
    server_name ws.example.com;
    
    location /ws/ {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
        proxy_read_timeout 86400s;
    }
}

7.2 Socket.IO代理 #

nginx
location /socket.io/ {
    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_set_header X-Real-IP $remote_addr;
}

八、不同协议代理 #

8.1 FastCGI代理 #

nginx
location ~ \.php$ {
    fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

8.2 uWSGI代理 #

nginx
location / {
    include uwsgi_params;
    uwsgi_pass unix:/var/run/uwsgi/app.sock;
    uwsgi_read_timeout 60s;
}

8.3 SCGI代理 #

nginx
location / {
    include scgi_params;
    scgi_pass 127.0.0.1:4000;
}

8.4 Memcached代理 #

nginx
location / {
    set $memcached_key $uri;
    memcached_pass 127.0.0.1:11211;
    default_type text/html;
    error_page 404 = @fallback;
}

location @fallback {
    proxy_pass http://backend;
}

九、错误处理 #

9.1 错误页面 #

nginx
location / {
    proxy_pass http://backend;
    proxy_intercept_errors on;
    error_page 500 502 503 504 /50x.html;
}

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

9.2 自定义错误响应 #

nginx
location / {
    proxy_pass http://backend;
    proxy_intercept_errors on;
    
    error_page 500 502 503 504 = @fallback;
}

location @fallback {
    proxy_pass http://backup_backend;
}

9.3 错误重试 #

nginx
location / {
    proxy_pass http://backend;
    proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
    proxy_next_upstream_tries 3;
    proxy_next_upstream_timeout 30s;
}

十、高级配置 #

10.1 请求体大小限制 #

nginx
location /upload/ {
    proxy_pass http://backend;
    client_max_body_size 100m;
    client_body_buffer_size 128k;
}

10.2 响应过滤 #

nginx
location / {
    proxy_pass http://backend;
    
    sub_filter 'http://backend' 'https://example.com';
    sub_filter_once off;
    sub_filter_types text/html text/css application/javascript;
}

10.3 IP透传 #

nginx
server {
    listen 80;
    server_name api.example.com;
    
    set_real_ip_from 10.0.0.0/8;
    set_real_ip_from 172.16.0.0/12;
    set_real_ip_from 192.168.0.0/16;
    real_ip_header X-Forwarded-For;
    real_ip_recursive on;
    
    location / {
        proxy_pass http://backend;
    }
}

十一、完整配置示例 #

nginx
upstream backend_servers {
    server 192.168.1.10:8080 weight=3;
    server 192.168.1.11:8080 weight=2;
    server 192.168.1.12:8080 backup;
    keepalive 32;
}

server {
    listen 80;
    server_name api.example.com;
    
    access_log /var/log/nginx/api.access.log;
    error_log /var/log/nginx/api.error.log;
    
    location / {
        proxy_pass http://backend_servers;
        
        proxy_http_version 1.1;
        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 Connection "";
        
        proxy_connect_timeout 30s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 16k;
        proxy_busy_buffers_size 24k;
        
        proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
        proxy_next_upstream_tries 3;
        
        client_max_body_size 50m;
    }
    
    location /health {
        proxy_pass http://backend_servers/health;
        access_log off;
    }
}

十二、总结 #

本章我们学习了:

  1. 反向代理原理:正向代理vs反向代理
  2. 基本配置:proxy_pass使用方法
  3. 请求头传递:常用请求头配置
  4. 超时配置:连接、发送、读取超时
  5. 缓冲配置:请求和响应缓冲
  6. 代理缓存:缓存配置和状态
  7. WebSocket代理:长连接配置
  8. 错误处理:错误页面和重试

掌握反向代理后,让我们进入下一章,学习负载均衡配置!

最后更新:2026-03-27