日志分析:从 access.log 里读出真问题
用几条命令找出 404 重灾区、异常 UA、爬虫占比、慢请求与被扫描路径。
访问日志是最被低估的诊断工具。它记录了谁在什么时候、用什么方式、访问了什么、得到什么结果。
先看格式
默认 combined 格式:
$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"
字段依次是:IP、时间、请求行、状态码、字节数、来源、UA。
五个高频分析
1. 404 最多的路径
awk '$9==404 {print $7}' access.log | sort | uniq -c | sort -rn | head -20
如果大量 404 来自站内链接,说明改版没做映射;如果来自随机字符串,说明在被扫描。
2. 爬虫占比
grep -i -E "baiduspider|googlebot|bingbot|bytespider" access.log | wc -l
awk '{print $1}' access.log | sort -u | wc -l
爬虫请求占比超过 60% 且不带来流量,需要检查是否有大量无效 URL 被抓取。
3. 异常 UA 与扫描器
awk -F'"' '{print $6}' access.log | sort | uniq -c | sort -rn | head -15
大量空 UA、sqlmap、nikto、masscan 之类的 UA,说明被自动化扫描。可以考虑在 nginx 层直接 444。
4. 单 IP 高频
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -10
单 IP 一分钟几百次请求,基本是批量抓取或 CC。
5. 慢请求
需要 nginx 配 $request_time:
log_format main '$remote_addr [$time_local] "$request" $status '
'$body_bytes_sent $request_time "$http_referer" "$http_user_agent"';
awk '$NF>2' access.log | head # 粗略,需按实际字段位置调整
日志切割
不做切割,日志会撑满磁盘。用 logrotate:
/www/wwwlogs/*.log {
daily
rotate 14
compress
missingok
notifempty
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 $(cat /var/run/nginx.pid)
endscript
}
kill -USR1 让 nginx 重新打开日志文件,比 reload 更轻。
从日志看安全
- 大量
POST /wp-login.php或/xmlrpc.php→ 后台爆破 - 大量
GET /wp-content/.../shell.php→ 后门探测 - 请求里带
../或%2e%2e→ 路径穿越尝试 - 单个 IP 遍历
/.env、/.git/config→ 源码泄露扫描
发现后先封 IP,再检查文件是否真的存在。.env、.git 能被访问是严重问题,nginx 里必须显式拒绝:
location ~ /\.(git|env|svn) { return 404; }
日志保留多久
- 访问日志:14 天(排障够用)
- 错误日志:30 天
- 安全事件相关:导出归档,保留 6 个月
相关:网站被挂马的 12 个信号。