温馨提示×

如何统计nginx访问日志

小樊
57
2026-09-07 09:16:35
栏目: 编程语言

统计 Nginx 访问日志通常需要结合 access.log 格式 和 Linux 命令行工具(如 awk、grep、sort、uniq 等)。下面从基础统计到实战示例系统说明。


一、先确认 Nginx 日志格式

常见默认格式(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:客户端浏览器

二、常见统计需求与命令

1️⃣ 统计访问 IP 排名(Top 10)

awk '{print $1}' access.log | sort | uniq -c | sort -nr | head

2️⃣ 统计请求 URL(Top 10)

awk '{print $7}' access.log | sort | uniq -c | sort -nr | head

$7 通常是 /index.html 这类 URL(视日志格式而定)


3️⃣ 统计 HTTP 状态码分布

awk '{print $9}' access.log | sort | uniq -c | sort -nr

常见状态码:

  • 200:正常
  • 404:未找到
  • 500:服务器错误

4️⃣ 统计某个时间段的访问量

例如:统计 10:00–11:00

awk '$4 >= "[10:00:00" && $4 <= "[11:00:00"' access.log | wc -l

5️⃣ 统计访问最多的 User-Agent

awk -F'"' '{print $6}' access.log | sort | uniq -c | sort -nr | head

6️⃣ 统计爬虫 / 搜索引擎访问

grep -i "bot" access.log | wc -l

或:

awk -F'"' '$6 ~ /bot/ {print $6}' access.log | sort | uniq -c

7️⃣ 统计大文件下载(>1MB)

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

四、使用 GoAccess(可视化神器)

安装

yum install goaccess   # CentOS
apt install goaccess   # Ubuntu

实时分析

goaccess access.log -o report.html --log-format=COMBINED

浏览器打开 report.html 即可看到:

  • 访客数
  • 带宽
  • 状态码
  • 热门页面

五、进阶:日志分割(防止太大)

logrotate 示例

/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

如果你有 具体的日志格式 或 想分析的问题(如攻击、慢请求、某接口异常),可以把日志样例发我,我可以帮你写精准命令。

0 踩