Nginx日志分析是识别和防范恶意访问的重要手段。以下是一些关键步骤和技巧,帮助你通过Nginx日志识别恶意访问:
首先,确保你的Nginx配置文件中设置了详细的日志格式。常用的日志格式包括combined和common,但你可以根据需要自定义日志格式。
http {
log_format custom '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log custom;
}
在分析日志时,关注以下几个关键字段:
$remote_addr: 客户端的IP地址。$status: HTTP状态码。$body_bytes_sent: 发送的字节数。$http_referer: 引用页面。$http_user_agent: 用户代理字符串。$http_x_forwarded_for: 客户端的真实IP地址(如果使用了代理)。短时间内大量相同的请求可能是恶意爬虫或DDoS攻击。
awk '{print $1, $4}' access.log | sort | uniq -c | sort -nr | head -n 10
大量的404错误可能是扫描行为。
awk '$status == 404 {print $1, $4}' access.log | sort | uniq -c | sort -nr | head -n 10
使用常见的恶意User-Agent字符串。
awk '$http_user_agent ~ /bot|spider|curl|wget/' access.log | sort | uniq -c | sort -nr | head -n 10
单个IP地址在短时间内发起大量请求。
awk '{print $1, $4}' access.log | cut -d: -f1 | sort | uniq -c | sort -nr | head -n 10
使用一些日志分析工具可以更高效地识别恶意访问:
一旦识别出恶意访问,可以采取以下措施:
iptables或ufw封禁恶意IP。limit_req模块限制请求频率。# 封禁单个IP
iptables -A INPUT -s 192.168.1.100 -j DROP
# 封禁多个IP
iptables -A INPUT -m iprange --src-range 192.168.1.100-192.168.1.110 -j DROP
通过以上步骤和技巧,你可以有效地识别和防范Nginx日志中的恶意访问。