unattended-upgrades
bash
# /etc/sysctl.conf
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
server {
# 禁用不必要的HTTP方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
# 安全头部
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'";
# 隐藏服务器信息
server_tokens off;
# 限制客户端请求体大小
client_max_body_size 1m;
}
# 禁用目录浏览
Options -Indexes
# 禁用服务器签名
ServerSignature Off
ServerTokens Prod
# 安全头部
Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-XSS-Protection "1; mode=block"
# 使用fail2ban自定义规则检测异常请求
[web-api-abuse]
enabled = true
filter = web-api-abuse
logpath = /var/log/nginx/access.log
maxretry = 5
findtime = 600
bantime = 3600
# Nginx速率限制
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
location /api/ {
limit_req zone=api burst=20 nodelay;
}
# 示例自动封锁脚本
#!/bin/bash
ABUSE_IP=$(tail -n 1000 /var/log/nginx/access.log | grep 'HTTP/[1-2].[0-1]\" 4[0-9][0-9]' | awk '{print $1}' | sort | uniq -c | sort -nr | head -n 1 | awk '{print $2}')
if [ ! -z "$ABUSE_IP" ]; then
iptables -A INPUT -s $ABUSE_IP -j DROP
echo "$(date) - Blocked IP: $ABUSE_IP" >> /var/log/auto_block.log
fi
通过以上多层次、创新性的防护措施,可以显著提高Linux服务器上Web接口的安全性,有效抵御各类网络攻击。