具有动态 basehref 的 Nginx 反向代理?

Nginx reverse proxy with dynamic basehref?

我已经使用 Angular 9 构建了一个 i18n 应用程序。我的 api 使用 /api/ url.但是自从我添加了 i18n,代理就不再工作了。 Rq:(Angular 添加 /fr/ 或 /en/ 到 url 因为我在编译时添加了 --baseHref 标志)

我想知道我如何告诉我的代理将我的应用程序的动态 basehref 添加到代理 url? 示例:如何将 GET myapp.com/fr/api/jobs 转换为 GET myapp.com/api/jobs ?

所以我有这个 nginx 配置:

location /fr/ { 
      autoindex on;
      try_files $uri$args $uri$args/ /fr/index.html;
  }

  location /en/ {
      autoindex on;
      try_files $uri$args $uri$args/ /en/index.html;
  }

  # Default to FR
  location / {
      # Autoindex is disabled here + the $uri$args/ is missing from try_files
      try_files $uri$args /fr/index.html;
  }

# Proxy to API call
  location */api/ {
    proxy_pass http://rest-api:9000;
  }

我尝试在 /api/ 之前收听所有内容,但这不起作用...

考虑这个位置:

  location ~ .*/api/(.*) {
    proxy_pass http://rest-api:9000/api/;
  }

这是一个正则表达式位置,可以匹配其中任意位置具有 /api/ 的任何 URI。例如,它将适用于:

example.com/api/foo/bar
example.com/api/
example.com/something/api/foo/bar

有一个捕获组 (.*) 用于记录 /api/ 之后的内容。它被保存为位置变量 </code>(因为它是表达式中的第一个也是唯一一个捕获组)。使用它,您可以构建到 API 后端的确切路径:</p> <pre><code>proxy_pass http://rest-api:9000/api/;

它将上面的例子变成:

proxy_pass http://rest-api:9000/api/foo/bar
proxy_pass http://rest-api:9000/api/
proxy_pass http://rest-api:9000/api/foo/bar

更新:当您在 proxy_pass 中使用正则表达式变量 </code> 时,您必须手动构建完整的 URL。如果您的 URL 可以包含参数(例如 <code>?foo=bar),您需要添加 $is_args$args。如果有任何参数,'$is_args' 负责添加 ?,'$args' 是实际参数。完整路径如下:

proxy_pass http://rest-api:9000/api/$is_args$args

奖励:您可以使用这个简单的服务器来查看 NGINX 将如何解释配置:

server {
  listen 8080;
  location ~ .*/api/(.*) {
    add_header Content-Type text/plain;
    return 200 http://api-server:9000/api/;
  }
}

访问其中包含 /api/ 的任何路径,您将在浏览器中看到如何解释您的当前位置。