Nginx默认日志通常位于:
- 访问日志:/var/log/nginx/access.log
- 错误日志:/var/log/nginx/error.log
在nginx.conf中可自定义日志格式:
http {
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
}
$remote_addr
: 客户端IP$time_local
: 本地时间$request
: 请求方法和URI$status
: HTTP状态码$body_bytes_sent
: 发送给客户端的字节数$http_referer
: 来源页面$http_user_agent
: 用户代理(浏览器信息)# 统计HTTP状态码
awk '{print $9}' access.log | sort | uniq -c | sort -rn
# 统计访问量前10的IP
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -n 10
# 查找404错误
grep ' 404 ' access.log
# 查找特定IP的访问
grep '192.168.1.100' access.log
# 安装
sudo apt-get install goaccess
# 基本使用
goaccess /var/log/nginx/access.log -a
# 生成HTML报告
goaccess /var/log/nginx/access.log -o report.html --log-format=COMBINED
完整日志分析解决方案: 1. Logstash配置示例:
input {
file {
path => "/var/log/nginx/access.log"
start_position => "beginning"
}
}
filter {
grok {
match => { "message" => "%{COMBINEDAPACHELOG}" }
}
date {
match => [ "timestamp", "dd/MMM/yyyy:HH:mm:ss Z" ]
}
}
output {
elasticsearch {
hosts => ["localhost:9200"]
}
}
现代监控方案: - Prometheus: 收集指标 - Loki: 日志聚合 - Grafana: 可视化展示
启用内置状态监控:
server {
listen 8080;
server_name localhost;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
}
输出示例:
Active connections: 291
server accepts handled requests
16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 106
使用nginx-exporter暴露指标:
# docker-compose示例
version: '3'
services:
nginx-exporter:
image: nginx/nginx-prometheus-exporter
ports:
- "9113:9113"
command:
- '-nginx.scrape-uri=http://nginx:8080/nginx_status'
# 检测扫描行为
grep -i 'scan|nmap|nikto|wpscan' access.log
# 检测SQL注入尝试
grep -i 'select.*from|union.*select|1=1' access.log
# 检测暴力破解
awk '{print $1,$7}' access.log | grep 'wp-login.php' | sort | uniq -c | sort -rn
配置示例:
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
port = http,https
logpath = /var/log/nginx/error.log
[nginx-badbots]
enabled = true
port = http,https
filter = nginx-badbots
logpath = /var/log/nginx/access.log
maxretry = 2
配置示例(/etc/logrotate.d/nginx
):
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
[ ! -f /var/run/nginx.pid ] || kill -USR1 `cat /var/run/nginx.pid`
endscript
}
# 查找并删除超过30天的日志
find /var/log/nginx -name "*.log" -type f -mtime +30 -delete
import pandas as pd
df = pd.read_csv(
'access.log',
sep=' ',
header=None,
names=['ip', 'ident', 'user', 'time', 'tz', 'request',
'status', 'size', 'referer', 'user_agent']
)
# 分析状态码分布
print(df['status'].value_counts())
# 分析热门请求
print(df['request'].value_counts().head(10))
结构化日志:使用JSON格式便于解析
log_format json_combined escape=json
'{'
'"time_local":"$time_local",'
'"remote_addr":"$remote_addr",'
'"request":"$request",'
'"status": "$status",'
'"body_bytes_sent":"$body_bytes_sent",'
'"http_referer":"$http_referer",'
'"http_user_agent":"$http_user_agent"'
'}';
分离日志:为不同虚拟主机配置独立日志文件
监控关键指标:
设置告警:对异常模式(如大量5xx错误)设置自动告警
长期归档:重要日志压缩后存储到对象存储(S3等)
通过以上全面的日志分析和监控手段,您可以有效掌握Nginx服务器的运行状况,及时发现并解决问题,优化性能并增强安全性。