在Nginx日志中过滤IP地址有多种方法,以下是几种常用的方式:
在nginx.conf或站点配置文件中添加条件:
# 允许特定IP访问
location / {
allow 192.168.1.100;
deny all;
}
# 或拒绝特定IP
location / {
deny 192.168.1.100;
allow all;
}
# 查看特定IP的访问记录
grep '192.168.1.100' /var/log/nginx/access.log
# 排除特定IP
grep -v '192.168.1.100' /var/log/nginx/access.log
# 统计IP访问次数
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr
# 统计特定IP的访问URL
awk '/192.168.1.100/ {print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -nr
goaccess /var/log/nginx/access.log --log-format=COMBINED
配置AWStats可以生成详细的IP访问统计报告
在Nginx配置中设置只记录特定IP的日志:
map $remote_addr $log_ip {
"192.168.1.100" 1;
default 0;
}
server {
...
access_log /var/log/nginx/access.log combined if=$log_ip;
}
基于Nginx日志自动封禁恶意IP:
# /etc/fail2ban/jail.local
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
port = http,https
logpath = /var/log/nginx/error.log
以上方法可以根据实际需求选择使用,对于安全分析和流量统计都非常有帮助。