zoukankan      html  css  js  c++  java
  • 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 变量已经增加到上述文件里面,可以记录到客户端请求体也就是域名后面进行的传参值,记录这个主要时判断用户名密码一类的,建议生产服务器也不要添加,日志量会增大。

  • 相关阅读:
    标签的讲解
    属性分类
    LeetCode 003. 无重复字符的最长子串 双指针
    Leetcode 136. 只出现一次的数字 异或性质
    Leetcode 231. 2的幂 数学
    LeetCode 21. 合并两个有序链表
    象棋博弈资源
    acwing 343. 排序 topsort floyd 传播闭包
    Leetcode 945 使数组唯一的最小增量 贪心
    Leetcode 785 判断二分图 BFS 二分染色
  • 原文地址:https://www.cnblogs.com/passzhang/p/13410262.html
Copyright © 2011-2022 走看看