1 基本配置
Nginx默认提供了两个日志文件 access.log和error.log,
- 通过access.log可以得到用户请求的相关信息;
- 通过error.log可以获取某个web服务故障或其性能瓶颈等信息。
2 默认日志格式
log_format combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
实际展示的日志样式
3 nginx常用内置变量
nginx常用的内置变量主要是用来分析日志中的http记录的,我们可以根据内置的变量精确的获取相关的信息
- 默认变量
$remote_addr 前一台主机的ip地址,不一定是真实的客户端IP
$remote_user 用于记录远程客户端的用户名称(一般为“-”)
$time_local 用于记录访问时间和时区
$request 用于记录请求的url以及请求方法
$status 响应状态码,例如:200成功、404页面找不到等。
$body_bytes_sent 给客户端发送的文件主体内容字节数
$http_referer 可以记录用户是从哪个链接访问过来的
$http_user_agent 用户所使用的代理(一般为浏览器)
- 其他常用变量
$request_uri 包含请求参数的原始URI,不包含主机名
$uri 不带请求参数的当前URI,不包含主机名
$http_x_forwarded_for 可以记录客户端IP,通过代理服务器来记录客户端的ip地址
$http_x_real_ip 可以记录客户端IP,通过代理服务器来记录客户端的ip地址
$args 这个变量等于请求行中的参数,同$query_string
$host 请求主机头字段,否则为服务器名称。
$scheme HTTP方法(如http,https)
$document_uri 与$uri相同
$document_root 当前请求文件配置文件中html的根目录即root值
$request_filename 当前请求的文件路径,由root或alias指令与URI请求生成
- 例:http://localhost:47123/qwe/asd/test.txt
$host localhost
$server_port 47123
$request_uri /qwe/asd/test.txt
$document_uri /qwe/asd/test.txt
$document_root /var/www/html
$request_filename /var/www/html/qwe/asd/test.txt
4 自定义日志格式
了解了内置变量之后, 我们就可以试试自己定义日志格式啦!
这里我们的需求是:
- 显示客户端的IP地址, 在转发过程中也能携带IP地址
- 能指定日志生成的路径
(1) /etc/nginx/nginx.conf
# 设定日志格式的方法: log_format 格式名称 "日志表现样式"
log_format proxy_format '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent "$http_referer"'
'"$http_user_agent" "$http_x_real_ip" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
(2) /etc/nginx/conf.d/xxx.conf
server {
listen 192.168.250.130:80;
location / {
proxy_pass http://192.168.250.130:8001;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
server {
listen 192.168.250.130:8001;
access_log /var/log/nginx/app1/access.log proxy_format; # 指定日志生成的路径
real_ip_header X-Forwarded-For; # 从哪个header头检索出要的IP地址
real_ip_recursive on; # 递归排除IP地址,ip串从右到左开始排除set_real_ip_from里面出现的IP
set_real_ip_from 192.168.0.0/16; # 真实服务器上一级代理的IP地址或者IP段
location / {
root /etc/nginx/html;
index 8001.html;
}
}
注: 下面日志中共3行, 前2行开启了set_real_ip_from 192.168.0.0/16, 最后1行注释掉了这句, 发现$remote_addr由192.168.250.1变为192.168.250.130