server_tokens off;
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
if ($server_protocol !~* "HTTP/1.1|HTTP/2.0") {
return 444;
}
set $block_sql_injections 0;
if ($query_string ~ "union.*select.*\(") {
set $block_sql_injections 1;
}
if ($query_string ~ "concat.*\(") {
set $block_sql_injections 1;
}
if ($block_sql_injections = 1) {
return 403;
}
location ~* "(\'|\")(.*)(drop|insert|md5|benchmark|or|and)(.*)(\'|\")" {
deny all;
}
location ~* "^.*(\<|\>|'|%27|%22|%3E|%3C).*" {
return 403;
}
load_module modules/ngx_http_modsecurity_module.so;
http {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
}
SecRuleEngine On
SecRequestBodyAccess On
SecRule REQUEST_HEADERS:Content-Type "text/xml" "id:'200000',phase:1,t:none,t:lowercase,pass,nolog,ctl:requestBodyProcessor=XML"
SecRule REQUEST_URI|REQUEST_BODY "\![\@\%\^\*\(\)\+\=\{\}\[\]\|\'\"\;\:\?\,\/\~\`]" "id:'210000',phase:2,deny,status:403,msg:'SQL Injection Attack'"
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
location /login {
limit_req zone=login burst=3 nodelay;
proxy_pass http://backend;
}
geo $bad_ips {
default 0;
include /etc/nginx/conf.d/blocked_ips.conf;
}
server {
if ($bad_ips) {
return 403;
}
}
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305';
ssl_prefer_server_ciphers on;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
location ^~ /uploads/ {
client_max_body_size 10M;
if ($request_filename ~* ^.*?\.(php|php5|sh|py|pl|exe)$) {
return 403;
}
}
location ~* /(uploads|images|assets)/.*\.(php|jsp|asp|aspx)$ {
deny all;
}
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" "$http_cookie"';
# 监控异常请求
tail -f /var/log/nginx/access.log | grep -E 'union.*select|benchmark|sleep\(|-- |\/etc\/passwd'
通过以上配置和策略,可以显著提高Nginx服务器的安全性,有效防范SQL注入和其他常见Web攻击。