主题
变量
Nginx 变量常用于日志、反向代理、重定向、条件判断和路径拼接。
请求相关
| 变量 | 说明 |
|---|---|
$request | 完整请求行,例如 GET /api HTTP/1.1 |
$request_method | 请求方法,例如 GET、POST |
$request_uri | 原始 URI,包含查询参数 |
$uri | 规范化后的 URI,不包含查询参数 |
$args | 查询参数,不包含 ? |
$query_string | 同 $args |
$is_args | 有查询参数时为 ?,否则为空 |
示例:
nginx
return 301 https://$host$request_uri;客户端相关
| 变量 | 说明 |
|---|---|
$remote_addr | 客户端 IP |
$remote_port | 客户端端口 |
$remote_user | HTTP Basic Auth 用户名 |
$http_user_agent | User-Agent 请求头 |
$http_referer | Referer 请求头 |
$http_<name> | 任意请求头,名称转小写,- 转 _ |
示例:
nginx
proxy_set_header X-Real-IP $remote_addr;主机与协议
| 变量 | 说明 |
|---|---|
$host | 请求 Host,优先来自请求头 |
$server_name | 当前匹配的 server_name |
$server_port | 当前 server 端口 |
$scheme | 请求协议,http 或 https |
$https | HTTPS 请求通常为 on |
示例:
nginx
proxy_set_header X-Forwarded-Proto $scheme;文件路径
| 变量 | 说明 |
|---|---|
$document_root | 当前请求的 root 路径 |
$request_filename | 当前请求映射到本地文件系统后的路径 |
$realpath_root | 解析符号链接后的 root 路径 |
示例:
nginx
try_files $uri $uri/ =404;代理相关
| 变量 | 说明 |
|---|---|
$proxy_add_x_forwarded_for | 原 X-Forwarded-For 加上当前客户端 IP |
$http_upgrade | WebSocket upgrade 请求头 |
$upstream_addr | 实际访问的上游地址 |
$upstream_status | 上游响应状态码 |
$upstream_response_time | 上游响应耗时 |
示例:
nginx
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;