【问题标题】:Full record url in nginx lognginx 日志中的完整记录 url
【发布时间】:2014-02-03 19:42:55
【问题描述】:

我们在生产环境中使用以下 nginx 站点配置文件。

log_format main '$http_x_forwarded_for - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" $request_time';



server {
        root /srv/www/web;
        server_name *.test.com;
        access_log /var/log/nginx/xxx.test.com.access.log main;

http://a.test.com/ping”和“http://b.test.com/ping”http请求都会记录在xxx.test.com.access.log文件中。

但是有一个问题,nginx没有在xxx.test.com.access.log中存储“域名”。

http://a.test.com/ping”和“http://b.test.com/ping”共享同一个请求“Get /ping”。

如何在 nginx 日志中记录“a.test.com”或“b.test.com”?

【问题讨论】:

    标签: nginx


    【解决方案1】:

    尝试在 log_format 中添加$host 变量:

    log_format main '$http_x_forwarded_for - $remote_user [$time_local] "$host" "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" $request_time';
    

    http://wiki.nginx.org/HttpCoreModule#.24host:

    $主机

    此变量等于请求或名称标头中的 Host 行 如果 Host 标头不是,则处理请求的服务器 可用。

    这个变量的值可能与 $http_host 不同 情况:1)当Host输入头不存在或值为空时, $host 等于 server_name 指令的值; 2)当值 of Host 包含端口号,$host 不包含该端口号。 从 0.8.17 开始,$host 的值总是小写。

    【讨论】:

    • 我们使用“server_name .test.com;”在 nginx.conf 中,所以 "$host" 是 ".test.com"。
    • 它适用于我在 Nginx 1.4.4 上。你有没有“重新加载”nginx?
    • 这是预定义的组合格式(添加了 $host),供任何需要的人使用;提问者的示例不包括$remote_addr,许多人会想要一个标准用户的IP 地址:log_format combined '$remote_addr - $remote_user [$time_local] ' '"$host" "$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent"'; 来源:nginx.org/en/docs/http/ngx_http_log_module.html
    • @TanHongTat 仅记录第一个请求主机名,同时不会记录请求。有没有办法同时记录请求
    【解决方案2】:

    如果你想记录完整的请求url,那么我的方法是

    log_format main '$http_x_forwarded_for - $remote_user [$time_local] '
    '"$request_method $scheme://$host$request_uri $server_protocol" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" $request_time';
    

    因此,将 $request 拆分为其组成部分并在中间弹出 $host。还可以让您查看请求是 http 还是 https。

    【讨论】:

    • 这种格式的优点是可以被标准格式的东西解析,比如filebeat nginx模块和logstash的grok模式
    • 谢谢。就我而言,$remote_addr 的第一个字段更好
    • $http_x_forwarded_for 可帮助您在多种情况下捕获客户端 IP,例如客户端直接连接以及客户端通过 Cloudflare 等代理连接。
    猜你喜欢
    • 2014-04-09
    • 1970-01-01
    • 2018-06-05
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 2018-12-20
    相关资源
    最近更新 更多