nginx访问日志要准确记录客户端真实ip,必须启用http_realip_module,配置set_real_ip_from声明可信代理网段、real_ip_header指定x-forwarded-for头、real_ip_recursive on开启递归解析,使$realip_remote_addr成为可靠的真实ip,并在log_format中优先使用该变量而非$http_x_forwarded_for。

Nginx 访问日志要全面记录客户端网络环境与连接特征,关键不是堆字段,而是有针对性地组合真实可用的变量,并确保代理链路中关键信息不丢失。
明确客户端真实 IP 与代理路径
默认 $remote_addr 在有 CDN 或反向代理时只记录上一跳地址(如 Nginx 自身或负载均衡器 IP),无法反映用户真实来源。必须配合 $http_x_forwarded_for 并在可信代理环境下启用 set_real_ip_from。
- 在
http或server块中配置可信代理段:set_real_ip_from 10.0.0.0/8; set_real_ip_from 192.168.0.0/16; real_ip_header X-Forwarded-For; real_ip_recursive on;
- 日志中优先使用
$realip_remote_addr(需ngx_http_realip_module支持),它比$http_x_forwarded_for更可靠,已自动解析并去重。
记录网络协议与传输层特征
HTTP 协议版本、TLS 状态、客户端连接方式直接影响性能与安全判断:
-
$server_protocol:显示HTTP/1.1或HTTP/2,可识别是否启用 HTTP/2 -
$scheme:http或https,快速区分是否走 TLS -
$ssl_protocol和$ssl_cipher:需启用 SSL 模块,记录 TLS 版本与加密套件(如TLSv1.3/TLS_AES_256_GCM_SHA384) -
$connection_requests:当前 TCP 连接上已处理的请求数,用于分析连接复用效率
捕获客户端设备与网络行为细节
仅靠 User-Agent 不足以还原真实环境,需补充上下文:
-
$http_user_agent:保留原始 UA 字符串,用于后续解析设备类型、OS、浏览器 -
$http_accept_language:识别用户语言偏好,辅助地域化分析 -
$http_upgrade:是否发起 WebSocket 升级(值为websocket) -
$request_time和$upstream_response_time:区分 Nginx 处理耗时与后端响应延迟 -
$bytes_sent与$bytes_received:收发字节数,可发现异常大请求或空响应
增强地理与网络质量维度(需额外模块)
若已编译 ngx_http_geoip2_module 或 ngx_http_geoip_module:
-
$geoip2_data_country_iso_code(GeoIP2)或$geoip_country_code(旧版):国家代码 -
$geoip_city、$geoip_region_name:城市与省份,需数据库支持 -
$http_via:显示代理链路(如1.1 varnish, 1.1 nginx),验证中间节点是否合规
推荐生产级日志格式示例
log_format full_client '$realip_remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time '
'$scheme $server_protocol $ssl_protocol "$ssl_cipher" '
'$http_x_forwarded_for "$http_via" '
'$geoip2_data_country_iso_code $geoip2_data_city_name '
'$bytes_sent $bytes_received';
access_log /var/log/nginx/access.log full_client;
该格式兼顾可读性与排错深度,不依赖外部解析即可定位多数网络层问题。注意:GeoIP 变量需提前加载数据库,$realip_remote_addr 需配合 real_ip 配置才有效。











