server_tokens off;
location / {
limit_except GET POST {
deny all;
}
}
more_clear_headers 'Server';
more_clear_headers 'X-Powered-By';
# 拦截常见SQL注入特征
set $block_sql_injections 0;
if ($query_string ~ "union.*select.*\(") {
set $block_sql_injections 1;
}
if ($block_sql_injections = 1) {
return 403;
}
# 添加XSS防护头
add_header X-XSS-Protection "1; mode=block";
# 只允许同源请求
add_header X-Frame-Options SAMEORIGIN;
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location / {
limit_req zone=one burst=20;
}
}
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location / {
limit_conn addr 10;
}
}
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384...';
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
# 阻止常见攻击特征
location / {
if ($http_user_agent ~* (nmap|nikto|wget|curl|libwww-perl)) {
return 403;
}
if ($args ~* "\.\./") {
return 403;
}
if ($request_uri ~* "(eval\()") {
return 403;
}
}
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
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';
map $status $loggable {
~^[23] 0;
default 1;
}
access_log /var/log/nginx/security.log security if=$loggable;
deny 192.168.1.1;
geo $blocked_country {
default 0;
CN 1;
RU 1;
}
server {
if ($blocked_country) {
return 403;
}
}
# 结合fail2ban使用
iptables -A INPUT -s 攻击IP -j DROP
grep "攻击特征" /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c | sort -nr
location / {
allow 信任IP;
deny all;
}
通过以上配置和策略,可以显著提升Nginx服务器的安全性,有效防御常见的Web攻击。实际部署时应根据业务需求调整安全策略,并定期更新规则以应对新型攻击手段。