Nginx是一个高性能的Web服务器/反向代理服务器,其模块化架构使其在Web安全领域具有高度灵活性。Nginx的核心安全特性包括:
ngx_http_access_module:
- 基于IP地址的访问控制
- 示例配置:
nginx
location /admin {
deny 192.168.1.1;
allow 192.168.1.0/24;
deny all;
}
ngx_http_auth_basic_module:
- 基本HTTP认证
- 示例:
nginx
location /secure {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
ngx_http_rewrite_module:
- URL重写与重定向
- 防御恶意请求示例:
nginx
if ($request_uri ~* "(\.\./|\.\.\\|\\\.\.)") {
return 403;
}
ngx_http_referer_module:
- 防盗链保护
- 示例:
nginx
valid_referers none blocked server_names *.example.com;
if ($invalid_referer) {
return 403;
}
ngx_http_headers_module:
- 添加安全相关HTTP头
- 推荐配置:
nginx
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Content-Security-Policy "default-src 'self'";
nginx
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
DDoS防护示例:
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
location / {
limit_req zone=one burst=20;
}
nginx
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;
nginx
if ($http_user_agent ~* (wget|curl|libwww-perl)) {
return 403;
}
创建安全映射表:
map $http_referer $bad_referer {
default 0;
"~*spammer.com" 1;
}
if ($bad_referer) {
return 403;
}
nginx
limit_conn_zone $binary_remote_addr zone=addr:10m;
最小权限原则:
user nginx;
worker_processes auto;
敏感信息保护:
server_tokens off;
文件访问限制:
location ~ /\.ht {
deny all;
}
日志安全配置:
log_format security '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" "$http_x_forwarded_for"';
定期审计配置:
nginx -t
测试配置实时监控:
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
异常检测:
location / {
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
}
应急响应:
nginx
deny 123.45.67.89;
nginx
error_page 503 /maintenance.html;
location = /maintenance.html {
root /usr/share/nginx/html;
internal;
}
通过合理配置Nginx模块和对象类型,可以构建强大的Web安全防御体系,有效抵御各类网络攻击。