【问题标题】:Use Location to Redirect Nginx to Specific Docker Container使用 Location 将 Nginx 重定向到特定的 Docker 容器
【发布时间】:2021-11-17 05:10:53
【问题描述】:

我有 3 个 .net 核心 api 在 docker 容器中运行,通过 docker compose 在 Nginx 反向代理后面编排。

我想这样做,以便我可以为所有 3 个 API 使用 1 个子域,但使用不同的 URI 路由分别重定向到每个 API,例如:

Docker Compose 服务名称:API_A、API_B、API_C

浏览器中的 URL -> 服务器上的资源

http://api.MyDomain.com/APIA/Swagger -> http://API_A:80/swagger

http://api.MyDomain.com/APIB/Swagger -> http://API_B:80/swagger

http://api.MyDomain.com/APIC/Swagger -> http://API_C:80/swagger

http://api.MyDomain.com/APIA/api/resource?query="a" -> http://API_A:80/resource?query="a"

http://api.MyDomain.com/APIB/api/resource?query="a" -> http://API_B:80/resource?query="a"

http://api.MyDomain.com/APIC/api/resource?query="a" -> http://API_C:80/resource?query="a"

到目前为止,我一直在使用 NGINX 代理管理器 UI 来执行此操作,但我认为这需要某种使用位置的 nginx 配置。

谁能给我一个完成上述任务的示例 nginx 配置?

我不确定这个操作叫什么。我会很感激有人给我词汇,让我更好地理解我的需求和 nginx 文档。

感谢您的建议。

【问题讨论】:

    标签: .net docker nginx docker-compose


    【解决方案1】:

    看来您想要的是在反向代理 nginx 配置中完成请求转发。

    您需要在 nginx.conf 中编辑一些行。

    根据此配置,您在http://api.MyDomain.com/APIA/swagger 发送的请求将替换与配置中存在的位置前缀匹配的位置前缀,并将其转发给http://API_A:80/swagger

    该配置导致将在此位置处理的所有请求传递到指定地址的代理服务器。

    • 请求 - http://{some ip/ domain}/APIA/xxxx
    • 转发到-http://API_A:80/xxxxproxy_pass中写的指定地址

    位置前缀匹配完成后,其余请求将附加到proxy_pass地址并以新地址的形式重写。

    server   { 
        listen 80;
        
        location  /APIA/api/ { 
          proxy_pass  http://API_A:80/;
        }
        location  /APIB/api/ { 
          proxy_pass  http://API_B:80/;
        }
        location  /APIC/api/ { 
          proxy_pass  http://API_C:80/;
        }
        location  /APIA/ { 
          proxy_pass  http://API_A:80/;
        }
        location  /APIB/ { 
          proxy_pass  http://API_B:80/;
        }
        location  /APIC/ { 
          proxy_pass  http://API_C:80/;
        }
        
      }
    

    根据官方文档 - Nginx official doc

    请注意,在上面的第一个示例中,代理服务器的地址后跟一个 URI,/link/。如果 URI 与地址一起指定,它将替换请求 URI 中与 location 参数匹配的部分。例如,这里带有 /some/path/page.html URI 的请求将被代理到 http://www.example.com/link/page.html。如果指定的地址没有 URI,或者无法确定要替换的 URI 部分,则传递完整的请求 URI(可能已修改)。

    【讨论】:

      猜你喜欢
      • 2020-12-10
      • 2017-05-07
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2021-12-27
      • 2021-09-15
      • 2018-05-23
      • 2019-03-11
      相关资源
      最近更新 更多