Nginx 访问日志中访问 IP 为空,通常不是 Nginx 本身的问题,而是日志变量取值来源异常。下面按最常见原因从高到低给你说明,并给出排查方法。
如果 Nginx 前面还有一层代理(如 CDN、负载均衡、WAF、另一层 Nginx、K8s Ingress),真实客户端 IP 在 X-Forwarded-For 或 X-Real-IP 头中,而 $remote_addr 取的是直连 IP。
$remote_addr 为空或固定为某个内网 IP- - [time] "GET / HTTP/1.1" 200
$remote_addr 只能拿到TCP 连接对端 IP✅ 使用真实 IP 变量
log_format main '$http_x_forwarded_for - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
或配合 realip 模块:
set_real_ip_from 10.0.0.0/8;
set_real_ip_from 127.0.0.1;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
然后仍可用 $remote_addr。
例如:
access_log logs/access.log '$remote_addr'
但:
nginx -T | grep log_format
确认 access_log 使用的是哪个格式。
某些情况下:
会产生不完整日志行,看起来像 IP 为空。
- - [10/Nov/2024:12:00:00 +0800] "-" 400 0 "-" "-"
通常伴随:
✅ 这是正常现象
$remote_addr 显示异常某些系统或日志分析工具:
::1 或 IPv6 地址识别为空✅ 检查:
grep "::" /var/log/nginx/access.log
allow/deny 或 return 444return 444;
✅ 属于正常行为
✅ 排查:
nginx -v
你可以按顺序检查:
$remote_addr 还是 $http_x_forwarded_for?realip 模块?http {
log_format main '$http_x_forwarded_for - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
}
你可以直接贴出:
nginx.conf 中的 log_format + access_log我可以帮你精确定位是哪一层导致 IP 为空。