入门教程 - 反向代理与 API 网关实践

知识库
知识库文档
/tech-stacks/nginx/tutorial/入门教程 - 反向代理与 API 网关实践.md

文档

Nginx 入门教程:反向代理与 API 网关实践

1. Nginx 的角色定位

在现代架构中,Nginx 常作为:

  • 反向代理:隐藏后端服务细节,统一入口
  • API 网关:认证、限流、日志、路由
  • 静态资源服务器:直连比应用服务器快 10 倍+
  • SSL 终结:统一管理证书,后端用 HTTP
客户端 → [HTTPS] → Nginx → [HTTP] → 后端服务

2. 核心指令详解

proxy_pass

location /api/ {
    proxy_pass http://backend/;  # 带尾部斜杠:/api/users → /users
    proxy_pass http://backend;   # 不带斜杠:  /api/users → /api/users
}

upstream 负载策略

upstream backend {
    # 轮询(默认)
    server srv1:8080;
    server srv2:8080;

    # 加权轮询
    server srv1:8080 weight=3;
    server srv2:8080 weight=1;

    # IP Hash(会话保持)
    ip_hash;

    # 最少连接
    least_conn;

    # 一致性 Hash(适合缓存场景)
    hash $request_uri consistent;
}

3. 限流实战

# 请求频率限制
limit_req_zone $binary_remote_addr zone=per_ip:10m rate=10r/s;
limit_req zone=per_ip burst=20 nodelay;

# 连接数限制
limit_conn_zone $binary_remote_addr zone=per_ip_conn:10m;
limit_conn per_ip_conn 10;

# 下载速度限制
limit_rate 100k;
limit_rate_after 1m;

4. 缓存配置

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m;
proxy_cache_key "$scheme$request_method$host$request_uri";

location /api/ {
    proxy_cache my_cache;
    proxy_cache_valid 200 10m;
    proxy_cache_valid 404 1m;
    proxy_cache_bypass $http_cache_control;  # 客户端可绕过缓存
}

5. 常见架构模式

模式一:前端 + API 同域

server {
    location / {
        root /var/www/frontend;  # 静态前端
    }
    location /api/ {
        proxy_pass http://backend;
    }
}

模式二:多服务路由

location /users/  { proxy_pass http://user-service; }
location /orders/ { proxy_pass http://order-service; }
location /payment/ { proxy_pass http://payment-service; }

6. 思考题

  1. 反向代理 vs 正向代理的区别?各解决什么问题?
  2. proxy_set_header X-Forwarded-For 有什么作用?
  3. Nginx 如何实现 WebSocket 代理?

信息

路径
/tech-stacks/nginx/tutorial/入门教程 - 反向代理与 API 网关实践.md
更新时间
2026/5/31