温馨提示×

怎样分析linux nginx日志

小樊
42
2026-09-05 17:36:17
栏目: 智能运维

分析 Linux 下的 Nginx 日志,通常分为日志位置确认 → 日志格式理解 → 手动/命令行分析 → 工具化分析几个阶段。下面从实用角度系统讲一下。


一、先确认 Nginx 日志在哪里

1. 查看 Nginx 配置

nginx -t

会显示配置文件路径,例如:

/etc/nginx/nginx.conf

2. 查找日志路径

grep -R "access_log" /etc/nginx/
grep -R "error_log" /etc/nginx/

常见默认路径:

  • 访问日志:/var/log/nginx/access.log
  • 错误日志:/var/log/nginx/error.log

二、理解 Nginx 日志格式

默认 access_log 格式(combined)

$remote_addr - $remote_user [$time_local] "$request" 
$status $body_bytes_sent "$http_referer" "$http_user_agent"

示例:

192.168.1.10 - - [12/Apr/2024:10:22:31 +0800] "GET /index.html HTTP/1.1" 200 2326 "https://www.baidu.com" "Mozilla/5.0"

字段含义:

  • remote_addr:客户端 IP
  • time_local:访问时间
  • request:请求方法和路径
  • status:HTTP 状态码
  • body_bytes_sent:返回字节数
  • referer:来源页
  • user_agent:客户端浏览器/爬虫

三、命令行基础分析(最常用)

1. 统计访问最多的 IP

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

2. 统计请求最多的 URL

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

3. 统计 HTTP 状态码分布

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

4. 查看 404 / 500 错误

grep " 404 " access.log
grep " 500 " access.log

5. 统计某时间段访问量

grep "12/Apr/2024:10:" access.log | wc -l

6. 统计爬虫(User-Agent)

grep -i "bot" access.log | awk '{print $1}' | sort | uniq -c

四、错误日志分析

查看错误日志

tail -f /var/log/nginx/error.log

常见错误类型

  • connect() failed:后端服务不可用
  • upstream timed out:反向代理超时
  • permission denied:文件权限问题
  • too many open files:连接数限制

五、使用现成工具(推荐)

1. GoAccess(实时可视化)

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

特点:

  • 终端或 HTML 报表
  • 实时统计 PV/UV/IP

2. Awstats

  • 适合长期统计
  • 配置稍复杂

3. ELK / Grafana + Loki

  • 企业级日志分析
  • 支持搜索、报警、可视化

六、实战分析思路(排障用)

✅ 网站变慢:

  • 看 5xx 比例
  • 看 upstream 响应时间(需开启 $request_time

✅ 被刷流量:

  • 看 IP 集中度
  • 看 User-Agent

✅ SEO 问题:

  • 看 404 页面
  • 看爬虫访问频率

七、建议开启的日志增强(nginx.conf)

log_format main '$remote_addr - $remote_user [$time_local] '
                '"$request" $status $body_bytes_sent '
                '"$http_referer" "$http_user_agent" '
                '$request_time $upstream_response_time';

如果你愿意,可以:

  • 发一段真实日志
  • 告诉我你是排错 / 统计 / 安全分析

我可以直接帮你写针对性分析命令或脚本

0