/var/log/nginx/access.log
/var/log/nginx/error.log
http {
access_log /path/to/access.log;
error_log /path/to/error.log;
}
Nginx默认使用combined格式,也可自定义:
log_format security '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
grep:基础过滤
grep "404" access.log
grep -E "POST|PUT|DELETE" access.log
awk:高级处理
awk '{print $1}' access.log | sort | uniq -c | sort -nr | head -20
cut:字段提取
cut -d' ' -f1 access.log | sort | uniq -c | sort -nr
GoAccess:实时可视化分析
goaccess access.log -o report.html --log-format=COMBINED
AWStats:详细统计分析
SQL注入:
grep -Ei "(select|union|insert|delete|update|drop|alter|truncate).*(from|into|where)" access.log
XSS攻击:
grep -Ei "(<script|javascript:|onerror=|onload=)" access.log
目录遍历:
grep -Ei "(\.\./|\.\.\\|%2e%2e|%252e)" access.log
暴力破解:
awk '{print $1,$7}' access.log | grep "wp-login.php" | awk '{print $1}' | sort | uniq -c | sort -nr
高频访问IP:
awk '{print $1}' access.log | sort | uniq -c | sort -nr | head -20
非200状态码:
awk '$9 != 200 {print $0}' access.log
大文件下载:
awk '$10 > 10000000 {print $7,$10,$1}' access.log | sort -nr
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
action = iptables[name=HTTP, port=http, protocol=tcp]
logpath = /var/log/nginx/error.log
maxretry = 3
#!/bin/bash
# 监控5分钟内404错误
ERROR_COUNT=$(awk -v d1="$(date --date="-5 min" "+%d/%b/%Y:%H:%M")" -v d2="$(date "+%d/%b/%Y:%H:%M")" '$0 > d1 && $0 < d2 && $9 == 404' access.log | wc -l)
if [ $ERROR_COUNT -gt 100 ]; then
echo "High 404 errors detected: $ERROR_COUNT" | mail -s "Nginx Alert" admin@example.com
fi
编辑/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
}
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 444;
}
server_tokens off;
通过系统化的日志分析和安全检测,可以显著提升Nginx服务器的安全性,及时发现并应对潜在威胁。