Nginx2026-04-15·8 分钟
Nginx 反向代理与 API 网关实践
总结 Nginx 作为反向代理和 API 网关的配置场景、路由与安全策略。
Nginx 反向代理与 API 网关实践
1. 基本反向代理配置
nginx
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}2. API 路由与版本管理
- 通过
location /api/v1/、location /api/v2/做版本路由。 rewrite可处理 URI 重写。
nginx
location /api/v1/ {
proxy_pass http://backend-v1/;
}3. 认证与流量控制
- 可针对安全接口配置基本认证或 JWT 验证。
- 使用限流
limit_req防止暴力请求。
4. 处理 CORS
nginx
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "GET,POST,OPTIONS";
add_header Access-Control-Allow-Headers "Authorization,Content-Type";- 对跨域接口提供必要响应头。
- 可使用
if ($request_method = OPTIONS)处理预检请求。
5. 负载均衡与故障转移
upstream可配置多后端。- 使用
max_fails和fail_timeout过滤不可用节点。
6. 缓存与加速
- 对 GET 接口可启用代理缓存。
- 对动态数据使用较短缓存时间。
7. 日志与调试
- 记录请求路径、状态码、响应时间。
access_log和error_log是排查 API 问题的关键。
8. 适用场景
- 小型服务网格或内部 API 网关。
- 对安全、路由、身份认证有统一入口需求。
Nginx反向代理API 网关