在Nginx中保障后端API安全需要多层次防护策略,以下是关键措施和配置建议:
HTTPS强制加密
server {
listen 443 ssl;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
# HTTP自动跳转HTTPS
if ($scheme != "https") {
return 301 https://$host$request_uri;
}
}
严格请求方法限制
location /api/ {
limit_except GET POST PUT DELETE {
deny all;
}
}
IP白名单控制
location /admin-api/ {
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
}
速率限制(防CC攻击)
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/s;
location /api/ {
limit_req zone=api_limit burst=50 nodelay;
}
JWT验证(需配合Lua模块)
location /protected-api/ {
access_by_lua_block {
local jwt = require("nginx-jwt")
jwt.auth({
secret = "your-256-bit-secret",
alg = "HS256"
})
}
}
请求头安全校验
location /api/ {
if ($http_user_agent ~* (wget|curl|nikto|sqlmap)) {
return 403;
}
add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "DENY";
}
反向代理隐藏真实后端
location /api/ {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_hide_header X-Powered-By;
}
敏感接口防护
location ~* /api/(users|admin)/.* {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
log_format api_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
access_log /var/log/nginx/api_access.log api_log;
nginx
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
# API安全网关配置示例
server {
listen 443 ssl;
server_name api.example.com;
# TLS配置
ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;
ssl_session_timeout 1d;
ssl_session_cache shared:MozSSL:10m;
# 安全头
add_header Strict-Transport-Security "max-age=63072000" always;
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'";
# API路由
location /v1/ {
# 访问控制
allow 192.168.1.0/24;
deny all;
# 速率限制
limit_req zone=api_limit burst=20;
# 代理配置
proxy_pass http://backend_cluster;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-API-Version 1.0;
# 连接超时控制
proxy_connect_timeout 3s;
proxy_read_timeout 10s;
}
# 管理接口
location /admin/ {
# 双重认证
auth_basic "Administrator Console";
auth_basic_user_file /etc/nginx/conf.d/.admin_passwd;
# IP限制
satisfy all;
allow 10.0.0.0/8;
deny all;
}
}
以上配置需要根据实际业务需求调整,建议结合OWASP API Security Top 10进行针对性防护。