45 lines
1.7 KiB
Bash
45 lines
1.7 KiB
Bash
|
|
#!/bin/bash
|
|||
|
|
# nginx 安全加固部署脚本(D 项)
|
|||
|
|
# - 备份已提前完成(/root/sec-hardening-backup-20260920-014533)
|
|||
|
|
# - 只在 http 上下文插入 limit_req_zone(不新增任何 stream 块)
|
|||
|
|
# - nginx -t 通过才 reload;失败立即回滚
|
|||
|
|
set -e
|
|||
|
|
BK=/root/sec-hardening-backup-20260920-014533
|
|||
|
|
|
|||
|
|
cp -f /tmp/app.anzhizhichong.com.conf /etc/nginx/conf.d/app.anzhizhichong.com.conf
|
|||
|
|
cp -f /tmp/test.anzhizhichong.com.conf /etc/nginx/conf.d/test.anzhizhichong.com.conf
|
|||
|
|
|
|||
|
|
python3 - <<'PY'
|
|||
|
|
p = '/etc/nginx/nginx.conf'
|
|||
|
|
s = open(p).read()
|
|||
|
|
if 'limit_req_zone' in s:
|
|||
|
|
print('limit_req_zone already present, skip insert')
|
|||
|
|
else:
|
|||
|
|
add = """ # ==== 安全加固:按客户端 IP 限流 zone(必须位于 http 上下文)====
|
|||
|
|
limit_req_zone $binary_remote_addr zone=auth_login_zone:10m rate=10r/m;
|
|||
|
|
limit_req_zone $binary_remote_addr zone=auth_challenge_zone:10m rate=20r/m;
|
|||
|
|
limit_req_zone $binary_remote_addr zone=uploads_zone:10m rate=120r/m;
|
|||
|
|
limit_req_status 429;
|
|||
|
|
"""
|
|||
|
|
i = s.index('http {') + len('http {')
|
|||
|
|
open(p, 'w').write(s[:i] + '\n' + add + s[i:])
|
|||
|
|
print('inserted limit_req_zone after http {')
|
|||
|
|
PY
|
|||
|
|
|
|||
|
|
echo "=== stream block count (must stay 1) ==="
|
|||
|
|
grep -c '^stream {' /etc/nginx/nginx.conf
|
|||
|
|
echo "=== limit_req_zone lines ==="
|
|||
|
|
grep -n 'limit_req_zone\|limit_req_status' /etc/nginx/nginx.conf
|
|||
|
|
echo "=== nginx -t ==="
|
|||
|
|
if nginx -t; then
|
|||
|
|
systemctl reload nginx
|
|||
|
|
echo "RELOAD OK"
|
|||
|
|
else
|
|||
|
|
echo "NGINX TEST FAILED -> ROLLBACK"
|
|||
|
|
cp -f "$BK/nginx.conf" /etc/nginx/nginx.conf
|
|||
|
|
cp -f "$BK/app.anzhizhichong.com.conf" /etc/nginx/conf.d/app.anzhizhichong.com.conf
|
|||
|
|
cp -f "$BK/test.anzhizhichong.com.conf" /etc/nginx/conf.d/test.anzhizhichong.com.conf
|
|||
|
|
nginx -t
|
|||
|
|
exit 1
|
|||
|
|
fi
|