nginx http模块的一些常用内置变量
				
									
					
					
						|  | 
							admin 2025年6月28日 22:15
								本文热度 1046 | 
					
				 
				服务器相关
- $server_name:虚拟主机名(server_name指令的配置)
- $document_root:root或alias命令配置的路径,可能是软链接。
- $realpath_root:当前请求对应到的真实路径,绝对路径。
- $request_filename:当前请求的文件路径,基于root或alias的配置组合出的路径
- $host:如果请求头中有Host就为该值,否则为server_name(nginx配置中的server)
- $limit_rate:limit_rate指令的设置值。
变量用途举例,记录日志:
http {
 log_format about_server_log 'server_addr:$server_addr,server_name:$server_name,server_port:$server_port\n'
        'document_root:$document_root,realpath_root:$realpath_root,request_filename:$request_filename\n'
        'host:$host,hostname:$hostname,nginx_version:$nginx_version\n'
        'pid:$pid,limit_rate:$limit_rate';
 server {
  listen 80;
  server_name localhost;
  access_log logs/server.log about_server_log;
        location / {
            root   /var/www/html;
            index  index.html index.htm;
        }
  location /api/ {
   proxy_pass http://localhost:8009/api/;
   limit_rate 100k;
  }
 }
}
请求http://xxx.xxx.xxx.xxx/5.jpg时,$document_root值为root指令配置的路径,为软链接,$realpath_root的值为真实物理路径。请求http://xxx.xxx.xxx.xxx/api/student/11时由代理服务响应,$request_filename值是基于root的配置与$uri组合得出的: 
客户端相关
- $binary_remote_addr:客户端IP的二进制
- $remote_user:Http Basic认证时的用户名
- $request:http请求,包括方法,uri,协议及版本
- $request_completion:请求完成时值为OK,否则空字符串
- $is_args:如果有请求参数值为?否则为空字符串
- $https:连接协议如果为https值为on,否则为空字符串
- $content_length:请求头中的Content-Length
- $content_type:请求头中的Content-Type
- $cookie_name:取cookie中key为name的值,name也只可以是其它名称
- $server_protocol:http协议版本
用于if判断举例:
server {
 listen 80;
 server_name localhost;
 location /api/ {
  # 传递Http Basic认证的用户名给上游服务
  proxy_set_header X-User $remote_user;
 # 判断请求方法
 if ($request_method != "GET") {
   return 405 "method not allowed";
  }
# 检查能处理的Content-Type类型
 if ($content_type != "application/json") {
   return 415 "Unsupported Media Type";
  } 
  proxy_pass http://localhost:8009/api/;
 } 
}
server {
 listen 81;
 server_name localhost;
 location / {
  # 将http请求重定向到https:
  if ($scheme = "http") {
   return 301 https://$host:443$request_uri;
  }
  ...
 } 
}
响应相关
- $sent_http_name:响应头中name值
代理相关
- $upstream_addr:上游服务器的IP和端口
- $upstream_status:上游服务器的响应状态码
- $upstream_response_time:上游服务的响应时长
- $proxy_host:proxy_pass指令中目标服务器的主机名和端口
- $proxy_port:proxy_pass指令中目标服务器的端口
阅读原文:原文链接
该文章在 2025/7/1 23:50:06 编辑过