作为IT工程师,我可以为您提供一套全面的Nginx防范脚本攻击的解决方案。以下是分层防御策略:
location / {
limit_except GET POST {
deny all;
}
}
server_tokens off;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;
client_max_body_size 8k;
set $block_sql_injections 0;
if ($query_string ~ "union.*select.*\(") {
set $block_sql_injections 1;
}
if ($block_sql_injections = 1) {
return 403;
}
set $block_xss 0;
if ($query_string ~ "<script.*>") {
set $block_xss 1;
}
if ($block_xss = 1) {
return 403;
}
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location / {
limit_req zone=one burst=5 nodelay;
}
}
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location / {
limit_conn addr 10;
}
}
load_module modules/ngx_http_modsecurity_module.so;
http {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
}
load_module modules/ngx_http_naxsi_module.so;
http {
include /etc/nginx/naxsi_core.rules;
server {
location / {
SecRulesEnabled;
DeniedUrl "/RequestDenied";
}
location /RequestDenied {
return 403;
}
}
}
geo $block_country {
default 0;
# 屏蔽高风险国家
CN 1;
RU 1;
KP 1;
}
server {
if ($block_country) {
return 403;
}
}
map $http_user_agent $blocked_agent {
default 0;
~*(wget|curl|libwww-perl|python|nikto|scan) 1;
~*(havij|sqlmap|bbqsql|absinthe|pangolin) 1;
}
server {
if ($blocked_agent) {
return 403;
}
}
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_ecdh_curve secp384r1;
ssl_session_timeout 10m;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
log_format security '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time '
'$http_x_forwarded_for';
access_log /var/log/nginx/security.log security;
这套方案提供了从基础到高级的多层防护,能有效抵御大多数脚本攻击。根据您的具体业务需求,可以适当调整其中的参数和规则。