以下是一个关于Nginx作为API网关的详细配置示例,涵盖路由、负载均衡、安全防护、性能优化等核心功能:
一、基础架构配置
# 全局配置块
user nginx;
worker_processes auto; # 自动匹配CPU核心数
worker_rlimit_nofile 65535; # 最大文件描述符数
events {
worker_connections 65535;
use epoll; # Linux高效事件模型
multi_accept on; # 批量接受连接
}
# HTTP核心配置块
http {
# 定义共享内存区(用于限流/健康检查)
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/s; # 全局限速区
limit_conn_zone $binary_remote_addr zone=conn_limit:10m; # 连接数限制
# 包含MIME类型与自定义日志格式
include /etc/nginx/mime.types;
log_format api_gateway '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'rt=$request_time uct="$upstream_connect_time" '
'uht="$upstream_header_time" urt="$upstream_response_time" '
'"$http_x_forwarded_for"';
# 定义后端服务组
upstream auth_service {
zone auth_service 64k;
server 10.0.0.10:8080 weight=5;
server 10.0.0.11:8080 weight=3;
keepalive 32; # 长连接保持数
health_check interval=10s fails=3 passes=2; # 健康检查
}
upstream payment_service {
least_conn; # 最少连接算法
server 10.0.0.20:8080;
server 10.0.0.21:8080 backup; # 备用节点
}
# 主服务器配置
server {
listen 443 ssl http2;
server_name api.example.com;
# SSL证书配置
ssl_certificate /etc/nginx/ssl/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/privkey.pem;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_protocols TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256;
# HTTP强制跳转
if ($scheme = http) {
return 301 https://$host$request_uri;
}
# 全局安全头
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options DENY;
add_header Content-Security-Policy "default-src 'self';";
# 路由配置
location /auth/ {
limit_req zone=api_limit burst=200 nodelay; # 突发200请求/秒
limit_conn conn_limit 50; # 单IP最大50并发连接
proxy_pass http://auth_service;
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 5s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
# 缓冲区配置
proxy_buffer_size 4k;
proxy_buffers 8 16k;
proxy_busy_buffers_size 32k;
}
location /payment/ {
auth_basic "API Authentication"; # 基础认证
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://payment_service;
proxy_http_version 1.1; # 启用HTTP/1.1长连接
proxy_set_header Connection ""; # 清除Connection头(WebSocket必需)
}
# 敏感路径防护
location ~ /(\.env|\.git|wp-config) {
deny all;
return 404;
}
# 自定义错误处理
error_page 502 /502.html;
location = /502.html {
internal;
root /usr/share/nginx/html;
}
# 访问日志
access_log /var/log/nginx/api_access.log api_gateway;
error_log /var/log/nginx/api_error.log warn;
}
# HTTP服务配置(强制HTTPS)
server {
listen 80;
server_name api.example.com;
return 301 https://$host$request_uri;
}
}
二、高级功能扩展
1. API密钥验证
location /secure-api/ {
# 验证API密钥(通过请求头或查询参数)
if ($arg_api_key != "secret-key-123") {
return 403 "Forbidden";
}
proxy_pass http://backend_service;
}
2. 请求签名验证(需Lua模块)
http {
lua_shared_dict api_keys 10m; # 共享内存存储密钥
init_by_lua_block {
api_keys:set("client1", "hmac-sha256-key")
}
location /signed-api/ {
access_by_lua_block {
local signature = ngx.req.get_headers()["X-API-Signature"]
local client_id = ngx.req.get_headers()["X-API-Client"]
local key = api_keys:get(client_id)
-- 验证签名逻辑(需自行实现)
if not verify_signature(key, signature) then
ngx.exit(403)
end
}
proxy_pass http://backend_service;
}
}
3. 请求体大小限制
location /upload/ {
client_max_body_size 100M; # 限制上传文件大小
client_body_buffer_size 50M;
proxy_pass http://storage_service;
}
4. 请求压缩与缓存
location /static/ {
gzip on;
gzip_types text/css application/javascript;
gzip_proxied expired no-cache no-store private auth;
proxy_cache cache_zone;
proxy_cache_valid 200 302 7d; # 缓存成功响应7天
proxy_cache_use_stale error timeout updating; # 后端故障时使用过期缓存
proxy_pass http://static_service;
}
三、监控与维护配置
1. 实时状态监控
server {
listen 8080;
server_name status.example.com;
location /nginx_status {
stub_status on;
allow 192.168.1.0/24;
deny all;
}
location /upstream_status {
upstream_conf; # Nginx Plus专用状态页
allow 192.168.1.0/24;
deny all;
}
}
2. 日志分析配置
# 实时分析API调用情况
tail -f /var/log/nginx/api_access.log | awk '{print $7 " " $9}' | sort | uniq -c
# 统计慢请求(>5s)
awk '$NF > 5 {print $0}' /var/log/nginx/api_access.log
四、配置验证与优化
-
语法检查
nginx -t -c /etc/nginx/nginx.conf
-
性能调优建议
- 调整
worker_connections
匹配实际并发量 - 对高频API路径启用
proxy_cache
- 使用
tcp_nopush
和tcp_nodelay
优化TCP传输 - 定期执行
nginx -s reload
热加载配置
- 调整
-
安全加固措施
- 通过
ssl_stapling
启用OCSP装订 - 使用
ssl_session_ticket_key
配置会话票据 - 定期轮换SSL证书和API密钥
- 通过
该配置示例实现了API网关的核心功能,可根据实际需求扩展以下方向:
- 集成JWT/OAuth2认证(需Lua模块)
- 添加速率限制策略(令牌桶算法)
- 实现灰度发布(通过权重路由)
- 配置服务发现(与Consul/Etcd集成)
建议通过压力测试工具(如wrk)验证配置效果,并结合APM工具(如Prometheus+Grafana)构建完整监控体系。