Nginx 日志变量(也叫内置变量)主要用于 log_format 中,用来定义访问日志(access log)和错误日志的格式。下面按常用程度和功能分类给你一个较完整的说明。
一、最常用日志变量
这些在 log_format 中几乎必用:
| 变量 |
含义 |
$remote_addr |
客户端 IP |
$remote_user |
客户端用户(HTTP 认证) |
$time_local |
本地时间(默认日志时间格式) |
$request |
完整的请求行(方法 + URI + 协议) |
$status |
HTTP 状态码 |
$body_bytes_sent |
发送给客户端的 body 字节数 |
$http_referer |
Referer |
$http_user_agent |
User-Agent |
$request_time |
请求总耗时(秒,毫秒级) |
✅ 示例(默认格式):
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
二、请求相关变量
| 变量 |
含义 |
$request_method |
请求方法(GET/POST 等) |
$request_uri |
原始请求 URI(含参数) |
$uri |
标准化后的 URI(不含参数) |
$args |
请求参数 |
$query_string |
同 $args |
$server_protocol |
协议版本(HTTP/1.1 等) |
三、主机与端口
| 变量 |
含义 |
$host |
请求 Host |
$server_name |
匹配的 server_name |
$server_port |
服务器端口 |
$server_addr |
服务器 IP |
四、客户端信息
| 变量 |
含义 |
$remote_port |
客户端端口 |
$binary_remote_addr |
二进制客户端 IP(常用于限速) |
$http_x_forwarded_for |
X-Forwarded-For(代理场景) |
$http_x_real_ip |
X-Real-IP |
五、响应相关变量
| 变量 |
含义 |
$status |
HTTP 状态码 |
$bytes_sent |
总发送字节数 |
$body_bytes_sent |
body 字节数 |
$sent_http_content_type |
响应 Content-Type |
$sent_http_content_length |
响应 Content-Length |
$sent_http_location |
响应 Location |
六、时间相关变量
| 变量 |
含义 |
$time_local |
本地时间 |
$time_iso8601 |
ISO 8601 时间(推荐) |
$msec |
毫秒时间戳 |
$request_time |
请求处理时间 |
$upstream_response_time |
后端响应时间(反向代理) |
$upstream_connect_time |
连接后端时间 |
$upstream_header_time |
后端响应头时间 |
七、反向代理 / 上游变量(upstream)
| 变量 |
含义 |
$upstream_addr |
上游服务器地址 |
$upstream_status |
上游返回状态码 |
$upstream_response_time |
上游响应时间 |
$upstream_connect_time |
连接上游时间 |
$upstream_header_time |
上游响应头时间 |
八、连接与性能
| 变量 |
含义 |
$connection |
连接序号 |
$connection_requests |
当前连接请求数 |
$request_length |
请求长度(请求行 + 头 + body) |
九、HTTPS / TLS
| 变量 |
含义 |
$scheme |
请求协议(http / https) |
$https |
是否 HTTPS(on / off) |
$ssl_protocol |
SSL 协议 |
$ssl_cipher |
SSL 加密套件 |
十、自定义 Header
所有请求头都可以用:
$http_header_name
例如:
$http_authorization
$http_token
十一、完整示例(生产推荐)
log_format json escape=json '{'
'"time":"$time_iso8601",'
'"host":"$host",'
'"remote_addr":"$remote_addr",'
'"x_forwarded_for":"$http_x_forwarded_for",'
'"method":"$request_method",'
'"uri":"$request_uri",'
'"status":$status,'
'"request_time":$request_time,'
'"body_bytes_sent":$body_bytes_sent,'
'"referer":"$http_referer",'
'"user_agent":"$http_user_agent"'
'}';
如果你愿意,我可以帮你:
- ✅ 设计 ELK / Grafana / 日志分析 的日志格式
- ✅ 给你 access log + error log 的最佳实践
- ✅ 针对 反向代理 / 负载均衡 / API 网关 的日志模板
直接告诉我你的使用场景即可。