Nginx在大规模Web安全防御中扮演着关键角色,其高性能、模块化设计和灵活的配置能力使其成为抵御各类网络攻击的重要工具。以下是Nginx在Web安全防御中的核心应用场景及实施方案:
隐藏敏感信息
server_tokens off; # 隐藏Nginx版本号
proxy_hide_header X-Powered-By; # 隐藏后端服务标识
禁用危险方法
if ($request_method !~ ^(GET|POST|HEAD)$) {
return 405;
}
文件权限控制
location ~* /\.(env|git|htaccess) {
deny all;
}
速率限制
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
location / {
limit_req zone=req_limit burst=20 nodelay;
}
连接数限制
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
location / {
limit_conn conn_limit 20;
}
SYN Flood防护
listen 80 backlog=4096 reuseport;
ModSecurity集成
load_module modules/ngx_http_modsecurity_module.so;
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
基础规则防护
location / {
# 阻断SQL注入尝试
if ($args ~* "union.*select|sleep\(|benchmark\(") {
return 403;
}
# 阻断XSS尝试
if ($request_uri ~* "<script>|alert\(") {
return 403;
}
}
强制HTTPS
server {
listen 80;
return 301 https://$host$request_uri;
}
现代加密套件
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;
HSTS头
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
IP黑白名单
geo $blocked {
default 0;
1.2.3.4/32 1; # 黑名单
192.168.0.0/24 0; # 白名单
}
location / {
if ($blocked) { return 403; }
}
Bot防护
map $http_user_agent $bad_bot {
default 0;
~*(bot|crawl|spider) 1;
}
0day漏洞应急
location / {
# 临时阻断特定路径访问(如Log4j漏洞)
location ~* /(jndi:|log4j) {
return 410;
}
}
安全日志格式
log_format security '$remote_addr - $http_x_forwarded_for - [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" $request_time';
实时日志分析
tail -f /var/log/nginx/security.log | grep -E ' 403 | 5[0-9]{2} '
边缘安全架构
用户 → CDN(Cloudflare/Akamai) → Nginx WAF层 → 后端集群
动态黑名单联动
# 与Fail2Ban集成
set $ban_ip 0;
if ($http_x_blacklist) { set $ban_ip 1; }
API安全网关
location /api/ {
limit_req zone=api_limit;
auth_request /auth-validate;
proxy_set_header API-Key $http_apikey;
}
nginx -t
和gixy
工具)通过以上策略组合,Nginx可有效防御CC攻击、SQL注入、XSS、暴力破解等90%以上的常见Web攻击,同时为业务提供高性能的安全服务。实际部署时应根据业务特点进行针对性调优。