Nginx 访问日志配置
Nginx 访问日志配置
访问日志是排查问题和分析流量的重要依据,配置好很有必要。
1. 默认日志位置
# 访问日志
/var/log/nginx/access.log
# 错误日志
/var/log/nginx/error.log
2. 日志格式
Nginx 默认有两种日志格式:
combined(默认)
log_format combined '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent"';
common
log_format common '$remote_addr [$time_local] "$request" $status $body_bytes_sent';
3. 自定义日志格式
在 nginx.conf 的 http 块添加:
http {
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
access_log /var/log/nginx/access.log main;
}
4. 常用日志变量
- $remote_addr: 客户端IP
- $time_local: 本地时间
- $request: 请求行
- $status: 状态码
- $body_bytes_sent: 发送字节数
- $http_referer: 来源页面
- $http_user_agent: 浏览器信息
- $request_time: 请求总耗时
- $upstream_response_time: 后端响应时间
5. 按站点分开日志
不同站点用不同日志文件:
server {
listen 80;
server_name a.com;
access_log /var/log/nginx/a.access.log;
}
server {
listen 80;
server_name b.com;
access_log /var/log/nginx/b.access.log;
}
6. 关闭日志
静态资源不记日志:
location ~* \.(jpg|jpeg|png|gif|css|js)$ {
access_log off;
}
7. 日志切割
Nginx 自带日志切割:
http {
# 每天切割,保留30天
access_log /var/log/nginx/access.log main;
log_not_found off;
}
也可以用 logrotate:
# 配置文件
/etc/logrotate.d/nginx
8. 分析日志
统计访问量
# 统计总请求数
wc -l /var/log/nginx/access.log
# 统计独立IP
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn
统计状态码
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c
统计访问最多的URL
awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10
总结
Nginx 访问日志配置要点:
- 默认日志在 /var/log/nginx/
- combined 是默认格式
- 自定义格式添加 $request_time 等变量
- 不同站点分开日志文件
- 静态资源可以关闭日志
- 日志要定期切割
- 用 awk 分析日志很方便
做好日志配置,排查问题和分析流量都有用。