Skip to content

变量

Nginx 变量常用于日志、反向代理、重定向、条件判断和路径拼接。

请求相关

变量说明
$request完整请求行,例如 GET /api HTTP/1.1
$request_method请求方法,例如 GETPOST
$request_uri原始 URI,包含查询参数
$uri规范化后的 URI,不包含查询参数
$args查询参数,不包含 ?
$query_string$args
$is_args有查询参数时为 ?,否则为空

示例:

nginx
return 301 https://$host$request_uri;

客户端相关

变量说明
$remote_addr客户端 IP
$remote_port客户端端口
$remote_userHTTP Basic Auth 用户名
$http_user_agentUser-Agent 请求头
$http_refererReferer 请求头
$http_<name>任意请求头,名称转小写,-_

示例:

nginx
proxy_set_header X-Real-IP $remote_addr;

主机与协议

变量说明
$host请求 Host,优先来自请求头
$server_name当前匹配的 server_name
$server_port当前 server 端口
$scheme请求协议,httphttps
$httpsHTTPS 请求通常为 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_forX-Forwarded-For 加上当前客户端 IP
$http_upgradeWebSocket upgrade 请求头
$upstream_addr实际访问的上游地址
$upstream_status上游响应状态码
$upstream_response_time上游响应耗时

示例:

nginx
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

基于 MIT 许可发布