作为IT工程师,我可以提供一套全面的Nginx配置方案来防范API接口攻击。以下是具体实施方法:
location /api/ {
if ($request_method !~ ^(GET|POST|PUT|DELETE)$ ) {
return 405;
}
# 其他配置...
}
server_tokens off;
add_header Allow "GET, POST, PUT, DELETE" always;
if ($request_method !~ ^(GET|POST|PUT|DELETE)$ ) {
return 405;
}
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/s;
location /api/ {
limit_req zone=api_limit burst=200 nodelay;
# 其他配置...
}
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=5r/m;
location /api/login {
limit_req zone=login_limit burst=5 nodelay;
# 其他配置...
}
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
limit_conn addr 10;
# 其他配置...
}
syn_flood on;
set $block 0;
if ($query_string ~* "union.*select.*\(") {
set $block 1;
}
if ($query_string ~* "concat.*\(") {
set $block 1;
}
if ($block = 1) {
return 403;
}
location ~* \.(php|asp|jsp|pl)$ {
deny all;
}
# 使用ModSecurity等WAF模块
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
location /api/ {
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
# 其他配置...
}
location /api/ {
# 验证Content-Type
if ($content_type !~ "application/json") {
return 415;
}
# 验证User-Agent
if ($http_user_agent ~* "(wget|curl|python|java|php)") {
return 403;
}
}
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;
map $status $loggable {
~^[23] 0;
default 1;
}
access_log /var/log/nginx/api_errors.log combined if=$loggable;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305';
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_session_tickets off;
以上配置需要根据实际业务需求进行调整,建议在测试环境验证后再部署到生产环境。