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

能否基于请求Host Header绑定API?API管理服务多域名路由需求

在Azure API管理中基于主机头路由到不同API

要在单个API管理(APIM)服务中实现基于HTTP主机头的路由,你可以通过自定义域名配置结合入站策略来实现,具体步骤如下:

1. 配置自定义域名

先给你的APIM服务添加两个自定义域名:

  • 为*.company.com配置域名解析(CNAME指向APIM网关的默认域名),并上传对应的SSL证书
  • 为*.anothercompany.com执行同样的操作,确保两个域名都能正常指向APIM服务

2. 创建目标API

在APIM中创建API1和API2,分别配置各自的后端服务、路径和其他必要设置(比如操作、策略等)。

3. 添加全局入站路由策略

在APIM的全局策略(或产品级策略,根据需求选择)中添加条件判断逻辑,根据请求的Host头转发到对应API的后端:

<choose>
    <!-- 匹配*.company.com的请求,转发到API1后端 -->
    <when condition="@(context.Request.Host.Host.MatchesWildcard("*.company.com"))">
        <set-backend-service base-url="https://api1-your-backend.com" />
        <!-- 可选:重写请求路径以匹配API1的后端路径规则 -->
        <rewrite-url template="/api1/{remaining}" />
    </when>
    <!-- 匹配*.anothercompany.com的请求,转发到API2后端 -->
    <when condition="@(context.Request.Host.Host.MatchesWildcard("*.anothercompany.com"))">
        <set-backend-service base-url="https://api2-your-backend.com" />
        <rewrite-url template="/api2/{remaining}" />
    </when>
    <!-- 处理未匹配的主机头 -->
    <otherwise>
        <return-response>
            <set-status code="404" reason="Unsupported Host" />
            <set-body>请求的主机头不被支持</set-body>
        </return-response>
    </otherwise>
</choose>

优化建议:使用命名值管理映射

如果需要更灵活的配置(比如后续修改主机头或后端地址),可以用APIM的命名值存储主机头和后端的映射关系:

  1. 在APIM中创建命名值:
    • Host_Company: *.company.com
    • Backend_Company: https://api1-your-backend.com
    • Host_Another: *.anothercompany.com
    • Backend_Another: https://api2-your-backend.com
  2. 修改策略引用命名值:
<choose>
    <when condition="@(context.Request.Host.Host.MatchesWildcard((string)context.NamedValues["Host_Company"]))">
        <set-backend-service base-url="@((string)context.NamedValues["Backend_Company"])" />
    </when>
    <when condition="@(context.Request.Host.Host.MatchesWildcard((string)context.NamedValues["Host_Another"]))">
        <set-backend-service base-url="@((string)context.NamedValues["Backend_Another"])" />
    </when>
    <otherwise>
        <return-response>
            <set-status code="404" />
            <set-body>Unsupported host header</set-body>
        </return-response>
    </otherwise>
</choose>

这种方式的核心是利用APIM的策略引擎,通过条件判断动态调整请求的后端服务,实现类似应用网关的监听器路由效果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 16:52:39