一、基础信息隐藏(必做)
1. 隐藏版本与服务标识
nginx
# nginx.conf http块
server_tokens off; # 关闭版本号显示
more_set_headers 'Server: Secure-Server'; # 自定义Server头(需headers-more模块)
more_clear_headers "X-Powered-By"; # 移除技术栈标识
2. 禁止敏感文件 / 目录访问
nginx
server {
# 禁止所有隐藏文件(.git/.svn/.env等)
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
# 禁止敏感后缀文件
location ~* \.(env|ini|sql|bak|log|conf|sh|py)$ {
deny all;
}
# 防目录遍历
if ($request_uri ~* \.\./) {
return 403;
}
}
二、访问控制与限流(防暴力破解 / CC)
1. 请求频率限制
nginx
# nginx.conf http块
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s; # 单IP每秒10请求
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=1r/m; # 登录接口更严格
server {
location / {
limit_req zone=req_limit burst=20 nodelay; # 突发20请求无延迟
}
location /login {
limit_req zone=login_limit burst=1 nodelay; # 登录接口限流
}
}
2. 并发连接限制
nginx
# nginx.conf http块
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
location / {
limit_conn conn_limit 10; # 单IP最大10连接
}
}
3. IP 黑白名单
nginx
# 全局黑名单
geo $blocked_ip {
default 0;
include /etc/nginx/blocked_ips.conf; # 外部黑名单文件
}
server {
if ($blocked_ip) {
return 444;
}
# 目录级白名单
location /admin {
allow 192.168.1.0/24;
deny all;
}
}
三、HTTP 方法与请求过滤
1. 限制危险 HTTP 方法
nginx
server {
if ($request_method !~ ^(GET|POST|HEAD)$) {
return 444; # 仅允许安全方法
}
}
2. 防 SQL 注入 / 恶意参数
nginx
server {
set $block 0;
# 拦截SQL注入特征
if ($request_uri ~* [;'<>\\\(\)]) { set $block 1; }
if ($args ~* [;'<>\\\(\)]) { set $block 1; }
if ($block) { return 444; }
}
四、SSL/TLS 安全配置(HTTPS 必做)
nginx
server {
listen 443 ssl http2;
ssl_certificate /path/to/fullchain.pem;
ssl_certificate_key /path/to/privkey.pem;
# 仅启用安全协议
ssl_protocols TLSv1.2 TLSv1.3;
# 强加密套件(前向保密)
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# 开启OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
}
五、安全响应头(浏览器防护)
nginx
server {
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Content-Security-Policy "default-src 'self'" always;
}
六、上传目录与脚本执行限制
nginx
server {
location /uploads {
alias /var/www/uploads;
# 禁止上传目录执行脚本
location ~* \.(php|pl|py|jsp|asp|sh|cgi)$ {
deny all;
}
}
}
七、进程权限与系统加固
- 以非 root 用户运行 Nginx(
user nginx;) - 最小化 Nginx 进程权限,禁止写权限
- 定期更新 Nginx 与系统补丁
- 配置日志轮转,审计 403/444 异常请求
八、验证与生效
bash
运行
nginx -t # 检查配置语法
nginx -s reload # 重载配置
curl -I https://your-domain.com # 验证响应头