微服务拆开之后,每个服务都想自己处理鉴权、限流、跨域、日志,重复且容易不一致。这时候通常会在最前面加一层网关。不一定要上专门的网关产品——如果需求是限流、缓存、灰度、统一 header,Nginx 完全够用,而且延迟最低。这篇整理这几块的实际配置。
限流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| limit_req_zone $binary_remote_addr zone=per_ip:10m rate=10r/s;
limit_req_zone $http_x_api_key zone=per_key:10m rate=100r/s;
limit_conn_zone $binary_remote_addr zone=conn_per_ip:10m;
server { location /api/ { limit_req zone=per_ip burst=20 nodelay; limit_req_status 429;
limit_conn conn_per_ip 20; limit_conn_status 429;
proxy_pass http://app_backend; }
location /api/expensive/ { limit_req zone=per_key burst=5; limit_req_status 429; proxy_pass http://app_backend; } }
|
rate=10r/s 的真实含义是”每 100ms 放行一个请求”,不是”每秒 10 个”——它是平滑的。burst=20 允许突发 20 个排队;加 nodelay 表示这 20 个立即放行而不排队等待。
这个参数是最容易配错的:不加 nodelay 时,用户会感觉到”偶发的等待”,因为请求在按 100ms 的间隔排队。对交互式接口,burst 为 rate 的 2-5 倍 + nodelay 是比较合理的组合。
限流一定返回 429 而不是 503,客户端和 CDN 对两者的处理不同。
缓存
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| proxy_cache_path /data/nginx/gateway levels=1:2 keys_zone=gw_cache:200m max_size=20g inactive=30m use_temp_path=off;
map $request_method $cacheable { default 0; GET 1; HEAD 1; }
location /api/catalog/ { proxy_cache_bypass $cookie_session; proxy_no_cache $cookie_session;
proxy_cache gw_cache; proxy_cache_key "$host$request_uri"; proxy_cache_valid 200 5m; proxy_cache_lock on; proxy_cache_use_stale updating error timeout http_500 http_502 http_503 http_504; proxy_cache_background_update on;
add_header X-Cache-Status $upstream_cache_status always; add_header X-Cache-Key "$host$request_uri" always;
if ($cacheable = 0) { add_header X-Cache-Status "BYPASS" always; }
proxy_pass http://app_backend; }
|
网关缓存的判断标准只有一条:响应是否与用户身份无关。商品目录、配置项、区域数据可以缓存;订单、个人资料一律不缓存。
proxy_cache_key 里如果想按语言、区域区分,加 $http_accept_language 这类变量即可,但别把 $request_time 这种每次都变的变量放进去,会直接让缓存失效。
灰度发布
按比例分流用 split_clients:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| split_clients "${remote_addr}${http_user_agent}" $variant { 10% canary; * stable; }
upstream app_stable { server 10.0.1.10:8080; } upstream app_canary { server 10.0.2.10:8080; }
server { location /api/ { proxy_pass http://app_$variant; add_header X-Variant $variant always; } }
|
split_clients 的哈希输入决定”同一个用户是否稳定落在同一组”。用 $remote_addr 保证同一个 IP 稳定命中同一边,不会每次刷新都切换;如果希望按用户维度,用 cookie 里的 uid 更准。
按 header 或 cookie 精确控制更适合内部测试:
1 2 3 4 5 6 7 8 9
| map $http_x_canary $variant { default stable; "1" canary; }
map $cookie_gray $v2 { default $variant; "on" canary; }
|
先内部用 header 验证,再按 1% → 10% → 50% 逐步放开,每步都对比错误率和 P99。
统一的横切配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| server { add_header Access-Control-Allow-Origin "$http_origin" always; add_header Access-Control-Allow-Methods "GET,POST,PUT,DELETE,OPTIONS" always; add_header Access-Control-Allow-Headers "Content-Type,Authorization,X-Request-Id" always; add_header Access-Control-Allow-Credentials "true" always;
if ($request_method = OPTIONS) { return 204; }
proxy_set_header X-Request-Id $request_id;
add_header X-Content-Type-Options nosniff always; add_header X-Frame-Options SAMEORIGIN always; add_header Referrer-Policy strict-origin-when-cross-origin always;
server_tokens off; }
|
$request_id 是 Nginx 内置变量,直接透传给后端,日志里带上它就能把网关日志和应用日志对上。这一条比任何 APM 都便宜。
Access-Control-Allow-Origin 回显 $http_origin 时,一定要配合白名单校验,否则等于允许任意域名带凭证访问:
1 2 3 4 5 6
| map $http_origin $cors_origin { default ""; "~^https://(www\.)?example\.com$" $http_origin; }
add_header Access-Control-Allow-Origin $cors_origin always;
|
需要写逻辑时
Nginx 的 if 有”if is evil”的说法,复杂逻辑不适合写在配置里。两种扩展方式:
- njs:官方模块,写 JavaScript,适合 JWT 校验、签名验证
- OpenResty / lua:生态更成熟,但引入 Lua 依赖
njs 校验 token 的骨架:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function verify(r) { const auth = r.headersIn['Authorization']; if (!auth || !auth.startsWith('Bearer ')) { r.error('missing token'); return 401; } const payload = JSON.parse(Buffer.from(auth.slice(7).split('.')[1], 'base64').toString()); if (payload.exp * 1000 < Date.now()) return 401; r.headersOut['X-User-Id'] = payload.sub; return 204; }
export default { verify };
|
1 2 3 4 5
| js_import auth from /etc/nginx/njs/auth.js;
location /api/ { js_content auth.verify; }
|
如果不是必须,我更倾向把鉴权放在应用层:网关一旦承担业务逻辑,就变成了新的单体,而且改一次配置要发一次网关。
踩过的坑
1. 限流把健康检查也限了
负载均衡的健康检查请求也被 limit_req 计数,导致真实用户被误限。健康检查单独放一个 location,不挂限流。
2. proxy_cache_valid 只写了 200
302 跳转和 404 走了默认不缓存,结果每次都在回源。按业务把 301/302/404 分别配好。
3. 灰度两套配置漂移
canary 和 stable 的 location 内容复制粘贴,改了一边忘了另一边,比对结果不可信。用 include 抽公共片段。
4. 忽略 OPTIONS 预检
跨域请求在预检阶段就 401 了,因为鉴权挂在 location 上。预检必须无条件返回 204。
小结
Nginx 做网关的边界很清楚:流量层面的能力归它,业务层面的能力归应用。限流、缓存、灰度、header、TLS、日志属于前者;鉴权、权限、参数校验属于后者。边界一旦模糊,网关会变成最脆弱的那个环节。