Nginx作为高性能的Web服务器和反向代理,其HTTP过滤器模块在Web安全防护中扮演着重要角色。以下是Nginx HTTP过滤器在Web安全中的主要应用场景和技术实现:
# 只允许GET和POST方法
if ($request_method !~ ^(GET|POST)$ ) {
return 405;
}
# 阻止User-Agent异常的请求
if ($http_user_agent ~* (wget|curl|libwww-perl) ) {
return 403;
}
# 添加安全头
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options SAMEORIGIN;
# 替换响应中的敏感信息
sub_filter 'password=****' 'password=[REDACTED]';
sub_filter_once off;
# 允许特定IP访问
location /admin {
allow 192.168.1.0/24;
deny all;
}
# 使用GeoIP模块限制国家访问
geo $allowed_country {
default no;
US yes;
CA yes;
GB yes;
}
server {
if ($allowed_country = no) {
return 403;
}
}
# 限制连接速率
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location / {
limit_req zone=one burst=5;
}
}
# 限制并发连接数
limit_conn_zone $binary_remote_addr zone=addr:10m;
location /download/ {
limit_conn addr 1;
}
# 强制HTTPS
server {
listen 80;
return 301 https://$host$request_uri;
}
# 安全SSL配置
server {
listen 443 ssl;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
add_header Strict-Transport-Security "max-age=63072000" always;
}
# 防止图片盗链
valid_referers none blocked server_names *.example.com;
if ($invalid_referer) {
return 403;
}
server_tokens off;
more_clear_headers Server;
more_clear_headers X-Powered-By;
# 自定义安全日志格式
log_format security '$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/security.log security if=$is_suspicious;
通过合理配置Nginx的HTTP过滤器,可以构建强大的Web应用安全防线,有效抵御多种网络攻击。