【问题标题】:Nginx exlude ips from logNginx 从日志中排除 ip
【发布时间】:2018-04-07 09:47:56
【问题描述】:

我在 Raspian 发行版上安装了一个 nginx 服务器,我想从 access_log 中排除我的本地 IP,我尝试了我在网络上可以找到的所有内容,但没有办法让它工作......

我试过这个解决方案:

map $remote_addr $log_ip { "192.168.2.1" 0; "192.168.2.2" 0; default 1; }

然后

access_log /var/log/nginx/proxy.log main if=$log_ip;

但是 Nginx 没有启动(状态显示它无法识别if=$log_ip;

我必须准确地解释我想要的:

  • 我有一个私人网站,我的树莓派上托管了一个授权访问(这个网站只是个人的)

  • 它在 Nginx 下运行,并受 Fail2ban 保护,它会扫描日志文件并在需要时禁止 IP。

  • 1234563写访问)
  • 所以我不需要记录我的本地 IP,但我想保留 access_log 以使 Fail2ban 正常工作。

【问题讨论】:

    标签: nginx logging


    【解决方案1】:

    将以下规则添加到 ngnix 配置的 http{} 上下文中。

        map $remote_addr $ip_anonym1 {
     default 0.0.0;
     "~(?P<ip>(\d+)\.(\d+)\.(\d+))\.\d+" $ip;
     "~(?P<ip>[^:]+:[^:]+):" $ip;
    }
    
    map $remote_addr $ip_anonym2 {
     default .0;
     "~(?P<ip>(\d+)\.(\d+)\.(\d+))\.\d+" .0;
     "~(?P<ip>[^:]+:[^:]+):" ::;
    }
    
    map $ip_anonym1$ip_anonym2 $ip_anonymized {
     default 0.0.0.0;
     "~(?P<ip>.*)" $ip;
    }
    
    log_format anonymized '$ip_anonymized - $remote_user [$time_local] ' 
       '"$request" $status $body_bytes_sent ' 
       '"$http_referer" "$http_user_agent"';
    
    access_log /var/log/nginx/access.log anonymized;
    

    这不会删除您的 IP,但可以创建一个匿名 IP 而不是实际 IP。

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      我找到了运行旧版本 Nginx (1.6.2) 的解决方案,我刚刚更新了最新版本,它可以工作...

      Nginx 1.7.0+ 允许在 access_log 指令本身中使用 if 条件。

      【讨论】:

        猜你喜欢
        • 2022-12-18
        • 2013-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多