nginx ip访问频率统计

发布于 2020-09-22  693 次阅读


日常我们会需要对网站的日志做分析,特别是对某一时段恶意采集的或者访问ip处理。这就用到统计日志中的ip访问频次。
我们nginx 需要打开日志记录工能main的配置,在nginx.conf中配置,当我们的域名使用cdn时候,我在访问日志看到的是cdn的ip,为了获取到真实ip,我们需要另外配置。
先说下不用cdn的log_format配置,配置完log_format 需要最终引用这个格式。

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
用一下的awk 命令即可得到ip的访问频次
awk '{print $1}' nginx_access.log|sort |uniq -c|sort -n|tail 
然后是使用cdn的ip访问频次统计,依旧用上面那个awk命令统计ip访问频次
    log_format  main  '$clientRealIP $remote_addr - 
                       $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

   map $http_x_forwarded_for  $clientRealIp {
                ""      $remote_addr;
                ~^(?P<firstAddr>[0-9\.]+),?.*$  $firstAddr;
        }

具体配置原理就不说了。