10 - 安全加固 / Security Hardening
安全加固 / Security Hardening
安全响应头
server {
# 防止点击劫持(Clickjacking)
add_header X-Frame-Options "SAMEORIGIN" always;
# 防止 MIME 类型嗅探
add_header X-Content-Type-Options "nosniff" always;
# XSS 过滤(旧浏览器)
add_header X-XSS-Protection "1; mode=block" always;
# 控制 Referrer 信息
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# Content Security Policy(严格策略示例)
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self';" always;
# 权限策略(限制浏览器 API 访问)
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
}
IP 访问控制
# 只允许特定 IP 访问管理后台
location /admin/ {
allow 10.0.0.0/8; # 内网
allow 203.0.113.50; # 办公室 IP
deny all; # 拒绝其他所有
proxy_pass http://backend;
}
# 拒绝特定 IP
location / {
deny 192.168.1.100;
deny 10.0.0.0/24;
allow all;
proxy_pass http://backend;
}
Basic Auth(基本认证)
# 生成密码文件
sudo apt install -y apache2-utils
sudo htpasswd -c /etc/nginx/.htpasswd admin
# 输入密码
# 添加更多用户
sudo htpasswd /etc/nginx/.htpasswd user2
location /admin/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://backend;
}
# 某些路径免认证
location /admin/public/ {
auth_basic off;
proxy_pass http://backend;
}
隐藏 Nginx 版本信息
http {
# 在 http 块中设置(全局生效)
server_tokens off;
}
默认(暴露版本):
Server: nginx/1.26.2
隐藏后:
Server: nginx
请求速率限制 / Rate Limiting
http {
# 定义限流区域
# key: 限流维度($binary_remote_addr = 客户端 IP)
# zone: 共享内存区域
# rate: 速率限制
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=1r/s;
server {
# API 限流
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
# burst=20: 允许突发 20 个请求
# nodelay: 突发请求不排队,直接处理
proxy_pass http://backend;
}
# 登录接口严格限流
location /api/auth/login {
limit_req zone=login_limit burst=3;
# 无 nodelay: 突发请求排队处理(更严格)
proxy_pass http://backend;
}
# 自定义限流错误页面
limit_req_status 429;
error_page 429 /429.html;
}
}
连接数限制
http {
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
# 每个 IP 最多 50 个并发连接
limit_conn conn_limit 50;
# 自定义连接限制错误
limit_conn_status 429;
}
}
User-Agent 过滤
# 封禁已知爬虫/恶意 User-Agent
map $http_user_agent $is_bad_bot {
default 0;
~*(bot|crawl|spider|scraper) 1;
~*(nikto|sqlmap|nmap) 1;
~*(masscan|zgrab) 1;
"" 1; # 空 User-Agent
}
server {
if ($is_bad_bot) {
return 403;
}
}
防盗链 / Hotlink Protection
location ~* \.(jpg|jpeg|png|gif|mp4|pdf)$ {
# 只允许来自本站或特定域名的 Referer
valid_referers none blocked server_names
*.example.com
example.com
*.trusted-site.com;
if ($invalid_referer) {
return 403;
# 或返回一个 "禁止盗链" 的图片
# rewrite ^ /images/hotlink-denied.png break;
}
# 同时配置 CORS(允许合法跨域)
add_header Access-Control-Allow-Origin "https://trusted-site.com";
}
请求体大小限制
# 全局限制
client_max_body_size 10m;
# API 上传接口可以放宽
location /api/upload/ {
client_max_body_size 100m;
proxy_pass http://backend;
}
# 请求头大小
client_header_buffer_size 4k;
large_client_header_buffers 4 32k;
🔴 高级 / Advanced — WAF 与安全架构
ModSecurity WAF
# 安装 ModSecurity 模块
# sudo apt install -y libnginx-mod-http-modsecurity
# 启用 ModSecurity
server {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsecurity/modsecurity.conf;
location / {
proxy_pass http://backend;
}
}
ModSecurity + OWASP CRS(核心规则集):
# 安装 OWASP Core Rule Set
cd /etc/nginx/modsecurity
git clone https://github.com/coreruleset/coreruleset.git
cp coreruleset/crs-setup.conf.example crs-setup.conf
# 在 modsecurity.conf 中包含 CRS
Include /etc/nginx/modsecurity/coreruleset/crs-setup.conf
Include /etc/nginx/modsecurity/coreruleset/rules/*.conf
防护能力:
- SQL 注入
- XSS 攻击
- 命令注入
- 路径遍历
- 文件包含
- 常见漏洞利用
geo 指令(地理封锁)
# 根据 IP 段封锁
geo $blocked_ip {
default 0;
103.21.244.0/22 1; # 可疑 IP 段
198.51.100.0/24 1;
include /etc/nginx/blocked_ips.conf; # 从文件加载
}
server {
if ($blocked_ip) {
return 403;
}
}
防 DDoS 策略
http {
# 多维度限流
limit_req_zone $binary_remote_addr zone=per_ip:50m rate=50r/s;
limit_req_zone $server_name zone=per_server:10m rate=1000r/s;
limit_conn_zone $binary_remote_addr zone=conn:50m;
# 使用 map 标记可疑请求
map $http_user_agent $suspicious {
default 0;
"" 1; # 空 UA
~*^$ 1;
}
server {
limit_req zone=per_ip burst=100 nodelay;
limit_req zone=per_server burst=2000;
limit_conn conn 100;
# 可疑请求更严格限流
if ($suspicious) {
set $limit_req_zone "strict";
}
# 关闭慢速连接
client_body_timeout 10s;
client_header_timeout 10s;
# 限制请求方法
if ($request_method !~ ^(GET|HEAD|POST|PUT|DELETE|PATCH)$) {
return 405;
}
}
}
安全检查清单
server {
# ✅ 1. 隐藏版本号
server_tokens off;
# ✅ 2. 安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# ✅ 3. 禁止访问隐藏文件
location ~ /\. {
deny all;
return 404;
}
# ✅ 4. 禁止访问备份文件
location ~* \.(bak|orig|save|swp|sql|conf)$ {
deny all;
return 404;
}
# ✅ 5. 限制请求体大小
client_max_body_size 10m;
# ✅ 6. 超时设置
client_body_timeout 10s;
client_header_timeout 10s;
keepalive_timeout 65s;
send_timeout 30s;
# ✅ 7. Buffer 溢出防护
client_body_buffer_size 16k;
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;
}
小结 / Summary
| 层级 | 你需要知道的 / What You Need to Know |
|---|
| 🟢 基础 | 安全 Header,IP 访问控制,Basic Auth,隐藏版本号 |
| 🟡 进阶 | limit_req/limit_conn 限流,UA 过滤,防盗链 |
| 🔴 高级 | ModSecurity WAF,geo 地理封锁,DDoS 防护策略 |
下一章:性能调优 / Performance Tuning