• Nginx记录用户请求Header到access log


    为了统计和其它用途,经常有人需要自定义Nginx日志,把http请求中的某个字段记录到日志中,刚好在看lua+nginx的文章,第一想到的是用lua赋值来做,但是想想有点小恶心,于是Google了一番,发现Nginx自己就能够记录收到的HTTP请求的头部数据,测试如下方法可用。

    测试环境Nginx 1.1.19

    把自定义头部加入日志

    为了方便,我们可能会在HTTP头里面加入特定的字符串,做一些标示,如果需要把标示打到日志里面,其实很简单。

    在nginx的http段里面对access log做如下的设置:

    ……
    http {
    ……
        log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                          '$status $body_bytes_sent "$http_referer" '
                          '"$http_user_agent" "$http_x_forwarded_for" "$http_mycheck"';
        access_log  logs/access.log  main;
    ……
    }
    ……
    

    我在日志格式的最后面加入了$http_mycheck,那么,Nginx会记录mycheck这个头部,保存到access log里面。

    重启Nginx,然后curl测试:

    ./nginx -s reload
    curl -H "mycheck: justtestlog" localhost/whatever.html
    curl localhost/whatever.html
    

    然后查看两次请求的日志记录

    tail -2 logs/access.log
    

    127.0.0.1 - - [xxx] "GET /whatever.html HTTP/1.1" 200 21 "-" "curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2" "-" "justtestlog"
    127.0.0.1 - - [xxx] "GET /whatever.html HTTP/1.1" 200 21 "-" "curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2" "-" "-"

    请求头部中没有mycheck字段的时候,日志字段里记为"-",header有mycheck字段的时候,最后一段是mycheck的值。

    记录用户访问的cookie

    ……
        set $dm_cookie "";
        if ($http_cookie ~* "(.+)(?:;|$)") {
            set $dm_cookie $1;
        }
     log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                          '$status $body_bytes_sent "$http_referer" '
                          '"$http_user_agent" "$http_x_forwarded_for" "$http_mycheck" "$dm_cookie"';
     access_log  logs/access.log  main;
    ……
    

    这样日志里面就可以看到cookie了,据说可以监控用户和行为。但是在实际中,cookie太长,加上cookie之后,日志量会成倍增长,会加大服务器的压力,如非必要,不建议在日志中添加该字段。

    记录用户访问的$request_body

    ……
     log_format  main  '$remote_addr - $remote_user [$time_local] "$request" $request_body '
                          '$status $body_bytes_sent "$http_referer" '
                          '"$http_user_agent" "$http_x_forwarded_for" "$http_mycheck" "$dm_cookie"';
     access_log  logs/access.log  main;
    ……
    

    $request_body 变量已经增加到上述文件里面,可以记录到客户端请求体也就是域名后面进行的传参值,记录这个主要时判断用户名密码一类的,建议生产服务器也不要添加,日志量会增大。

  • 相关阅读:
    宁泽涛世锦赛夺冠
    iOS手势识别的详细使用(拖动,缩放,旋转,点击,手势依赖,自定义手势)
    在xcode里面如何利用instrument
    Xcode 中搜索任何条件文本
    十大算法
    Object c中的alloc和init问题
    My97DaePicker 用js实现文本框日期相减求天数
    js 取消listbox选中的项
    C# OR/Mapping 数据处理模式学习
    ASP.NET实现列表页连接查询 拼接sql语句 绑定grivdView
  • 原文地址:https://www.cnblogs.com/Serverlessops/p/13410262.html
Copyright © 2020-2023  润新知