统计 Nginx 访问日志通常需要结合 access.log 格式 和 Linux 命令行工具(如 awk、grep、sort、uniq 等)。下面从基础统计到实战示例系统说明。
常见默认格式(nginx.conf):
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
对应字段含义:
$remote_addr:客户端 IP$time_local:访问时间$request:请求方法 + URL + 协议$status:HTTP 状态码$body_bytes_sent:返回字节数$http_user_agent:客户端浏览器awk '{print $1}' access.log | sort | uniq -c | sort -nr | head
awk '{print $7}' access.log | sort | uniq -c | sort -nr | head
$7通常是/index.html这类 URL(视日志格式而定)
awk '{print $9}' access.log | sort | uniq -c | sort -nr
常见状态码:
例如:统计 10:00–11:00
awk '$4 >= "[10:00:00" && $4 <= "[11:00:00"' access.log | wc -l
awk -F'"' '{print $6}' access.log | sort | uniq -c | sort -nr | head
grep -i "bot" access.log | wc -l
或:
awk -F'"' '$6 ~ /bot/ {print $6}' access.log | sort | uniq -c
awk '$10 > 1048576 {print $1, $7, $10}' access.log
awk '{print $4}' access.log | cut -d: -f1 | uniq -c
awk '{print $4}' access.log | cut -d: -f2 | uniq -c
yum install goaccess # CentOS
apt install goaccess # Ubuntu
goaccess access.log -o report.html --log-format=COMBINED
浏览器打开 report.html 即可看到:
/var/log/nginx/*.log {
daily
rotate 30
compress
missingok
notifempty
sharedscripts
postrotate
nginx -s reload
endscript
}
| 需求 | 推荐方式 |
|---|---|
| 快速统计 | awk + sort + uniq |
| 可视化 | GoAccess |
| 长期分析 | ELK / Grafana + Loki |
| 安全分析 | IP + UA + 404 |
如果你有 具体的日志格式 或 想分析的问题(如攻击、慢请求、某接口异常),可以把日志样例发我,我可以帮你写精准命令。