Nginx默认会记录基本的访问日志,通常在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地址 |
$remote_user |
认证用户名(如果有) |
$time_local |
本地时间 |
$request |
完整的原始请求行 |
$status |
响应状态码 |
$body_bytes_sent |
发送给客户端的字节数 |
$http_referer |
请求来源页 |
$http_user_agent |
客户端浏览器信息 |
$http_x_forwarded_for |
代理服务器IP(如果有) |
$request_time |
请求处理时间(秒) |
$upstream_response_time |
后端服务器响应时间 |
log_format detailed '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time '
'$scheme $host $server_port';
# 只记录状态码为4xx和5xx的请求
map $status $loggable {
~^[23] 0;
default 1;
}
access_log /var/log/nginx/error-requests.log combined if=$loggable;
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/example.com.access.log combined;
}
access_log /var/log/nginx/access.log combined buffer=32k flush=5m;
在/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
}
GoAccess - 实时日志分析工具
goaccess /var/log/nginx/access.log -a
AWK命令 - 简单分析
# 统计状态码
awk '{print $9}' access.log | sort | uniq -c | sort -rn
# 统计访问最多的IP
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -20
ELK Stack - Elasticsearch + Logstash + Kibana 完整日志分析方案
# 记录可疑请求
log_format security '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $http_x_forwarded_for';
map $request_uri $is_suspicious {
~*(\.\.|etc/passwd|\.php\?|wp-admin) 1;
default 0;
}
access_log /var/log/nginx/security.log security if=$is_suspicious;
对于高流量网站,考虑使用syslog直接发送日志到远程服务器
access_log syslog:server=10.0.0.1:514,facility=local7,tag=nginx,severity=info combined;
在生产环境中,避免记录静态资源请求以减少日志量
map $uri $static {
~*\.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|svg)$ 0;
default 1;
}
access_log /var/log/nginx/access.log combined if=$static;
通过合理配置Nginx日志,您可以全面监控网站访问行为,分析用户流量,排查问题并增强网站安全性。