Nginx提供了强大的日志功能,可以帮助你记录和分析HTTP请求。以下是完整的配置和使用方法:
在nginx.conf或站点配置文件中添加或修改access_log
指令:
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
- 完整的请求行(GET/POST等)$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';
access_log /var/log/nginx/access.log detailed 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
}
# 安装
sudo apt-get install goaccess # Debian/Ubuntu
sudo yum install goaccess # CentOS/RHEL
# 实时分析
goaccess /var/log/nginx/access.log -a
# 统计HTTP状态码
awk '{print $9}' access.log | sort | uniq -c | sort -rn
# 统计访问量最高的IP
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -20
# 统计访问量最高的URL
awk '{print $7}' access.log | sort | uniq -c | sort -rn | head -20
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"]
}
}
对于高流量网站,考虑使用缓冲日志:
access_log /path/to/log.gz combined gzip=1 buffer=32k flush=5m;
只记录必要的字段以减少I/O压力
对于特定路径禁用日志:
location /static/ {
access_log off;
}
log_format security '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time '
'Blocked: $http_x_blocked';
access_log /var/log/nginx/security.log security;
通过以上配置和分析方法,你可以全面掌握Nginx的HTTP请求情况,进行性能监控、安全分析和流量统计。