【问题标题】:Nginx reverse proxy with dynamic basehref?带有动态basehref的Nginx反向代理?
【发布时间】:2021-01-12 17:54:09
【问题描述】:

我使用 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/ {..}
  • 好的,我现在就试试。所以添加 ~.*/ 将监听 /api/ 之前的任何字符,然后仅使用 /api/ 重定向到 rest-api:9000 ?
  • 我不能在推荐中使用多行降价,所以我会放弃答案。

标签: angular nginx proxy internationalization reverse-proxy


【解决方案1】:

考虑这个位置:

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

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

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

有一个捕获组(.*) 记录/api/ 之后的任何内容。它被保存为位置变量$1(因为它是表达式中的第一个也是唯一一个捕获组)。使用它,您可以构建 API 后端的准确路径:

proxy_pass http://rest-api:9000/api/$1;

它将上面的例子变成:

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

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

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

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

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

【讨论】:

  • @Kubadev 很高兴为您提供帮助。不确定它是否对您有任何帮助,但您也可以使用另一个 (.*) 捕获前面的字符串。然后你可以将它作为 args 或类似的东西传递。
  • @Kubadev 如果您将位置设为~ (.*)/api/(.*),则前面的字符串将为$1,后面的字符串将为$2。你没忘记放花括号吧?
  • @Kubadev 抱歉,我以为您仍在研究前缀。可以使用?$args 添加请求参数。 $1 仅包含没有参数的位置。我还在我的问题中添加了“奖励内容”,这样您就可以尝试一定程度的舒适:)
  • 其实$is_args$args更好,所以用吧。
  • 没问题!再次感谢您的帮助。所以我的位置应该是:location ~ .*/api/(.*) {proxy_pass http://rest-api:9000/api/$1$is_args_$args; }? :) 哦!再次感谢奖励内容!!
猜你喜欢
  • 2019-01-12
  • 1970-01-01
  • 2014-10-27
  • 2018-12-12
  • 2018-02-09
  • 2016-03-31
  • 2021-01-10
  • 2021-01-29
  • 2017-10-22
相关资源
最近更新 更多