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

Nginx location指令中使用捕获变量匹配路径不生效问题咨询

问题解答

1. Nginx的location指令是否支持使用变量?

不支持。Nginx的location匹配规则是在配置文件加载阶段就完成解析预处理的,而你通过server_name正则捕获的$account是运行时(请求到达时)才会生成的变量,无法在预解析阶段被识别,因此你写的location /$account-backend/配置完全不会生效。

2. 该场景的正确实现方式

通过正则location匹配对应前缀的请求,额外增加租户一致性校验避免越权访问即可,修改后的完整配置如下:

server {  
  server_name ~^(?<account>.+)\.domain\.com$;
  root /var/www/html/folder-frontend/;
  index index.html;

  error_log /var/log/nginx/$account-access.log;
  access_log /var/log/nginx/$account-access.log;

  location / {
      try_files $uri /index.html;
  }

  # 正则匹配所有*-backend/开头的请求
  location ~ ^/(?<req_account>[^/]+)-backend/ {
      # 校验请求路径的租户标识和当前域名租户一致,拦截跨租户非法访问
      if ($req_account != $account) {
          return 403;
      }
      # 去除路径中的租户前缀后转发到后端,不需要去除前缀可删除该行
      rewrite ^/[^/]+-backend/(.*)$ /$1 break;
      proxy_pass http://service-backend;
      proxy_set_header HOST $account-backend.domain.co;
      proxy_http_version 1.1;
  }
}

补充说明

  • 正则location的优先级高于普通前缀location,不会和默认的location /规则冲突
  • 如果你不需要对路径前缀做裁剪,直接转发完整请求路径,删除rewrite行后将proxy_pass配置改为proxy_pass http://service-backend$request_uri;即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:30:04