You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx按路径动态代理到子域名配置报错:未知path变量

问题解决:Nginx报错unknown "path" variable

你的问题出在正则表达式的命名捕获组语法错误,不需要额外定义path变量,修正正则写法即可:

错误原因

在Nginx的正则location规则中,命名捕获组的正确格式是(?<变量名>匹配规则),而你写的(<path>.*)?没有使用?<>的标准语法,导致Nginx无法识别$path这个变量。

修正后的配置

server {
  listen 80;
  listen [::]:80;
  
  # 注意:$subdomain是在location块中定义的,server块的root指令无法提前获取该变量值,后续若用到root可能出现路径问题,建议根据实际需求调整
  root /var/www/private/$subdomain;
  
  index index.html index.htm index.nginx-debian.html;
  
  server_name external.com;
  
  # 修正命名捕获组语法,正确定义$subdomain和$path变量
  location ~ ^/(?<subdomain>[^/]+)/(?<path>.*)?$ {
    proxy_pass http://$subdomain.internal.com/$path;
    proxy_buffering off;
    proxy_set_header Host $http_host;
  }
}

额外说明

  1. 修正后,(?<path>.*)?会正确捕获请求URL中subdomain之后的所有路径内容:比如请求http://external.com/image/blue.png时,$subdomain为image,$path为blue.png,代理目标会自动匹配为http://image.internal.com/blue.png,完全符合你的需求。
  2. 关于root /var/www/private/$subdomain:该指令属于server块,而$subdomain是在location的正则规则里才被定义的,Nginx解析server块时还未生成这个变量的值,后续若访问该server下非代理的路径,可能出现路径错误,建议根据业务场景调整这部分配置。

内容的提问来源于stack exchange,提问作者CoopDaddio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 09:51:27