适用于:所有 API 管理层级
该 rewrite-uri 策略将请求URL从公开表单转换为网络服务期望的形式。
当您需要将一个用户友好或浏览器友好的URL转换为网络服务期望的URL格式时,请使用此策略。 仅在暴露替代 URL 格式时应用此策略,如干净的 URL、RESTful URL、用户友好的 URL 或纯结构性且不包含查询字符串、仅包含资源路径(方案和权威之后)的 SEO 友好 URL。 你通常为了美观、易用性或搜索引擎优化(SEO)目的而做出这种改变。
注意
按照策略声明中提供的顺序设置策略的元素和子元素。 详细了解如何设置或编辑 API 管理策略。
策略语句
<rewrite-uri template="uri template" copy-unmatched-params="true | false" />
属性
| 客户 | 说明 | 需要 | 默认 |
|---|---|---|---|
| 模板 | 包含任何查询字符串参数的实际 Web 服务 URL。 允许使用策略表达式。 使用表达式时,整个值必须是一个表达式。 | 是 | 空值 |
| copy-unmatched-params | 指定是否将原始 URL 模板中不存在的查询参数添加到重写模板定义的 URL 中。 允许使用策略表达式。 | 否 | true |
使用情况
使用注意事项
你只能通过策略添加查询字符串参数。 你不能在重写的 URL 里添加额外的模板路径参数。
例子
示例1:基础URL重写
在以下示例中,公共 URL 被重写为与后端服务 URL 格式一致,并基于其他逻辑包含查询参数。
公共 URL -
http://api.example.com/storenumber/ordernumber请求 URL -
http://api.example.com/v2/US/hardware/storenumber/ordernumber?City&State
<policies>
<inbound>
<base />
<rewrite-uri template="/v2/US/hardware/{storenumber}/{ordernumber}?City=city&State=state" />
</inbound>
<outbound>
<base />
</outbound>
</policies>
示例2:复制未匹配参数
在以下示例中,公共 URL 被重写为与后端服务 URL 格式一致,策略将未匹配的查询参数复制到新 URL。
<!-- Assuming incoming request is /get?a=b&c=d and operation template is set to /get?a={b} -->
<policies>
<inbound>
<base />
<rewrite-uri template="/put" />
</inbound>
<outbound>
<base />
</outbound>
</policies>
<!-- Resulting URL will be /put?c=d -->
例子3:不要复制未匹配的参数
在以下示例中,公共 URL 被重写为与后端服务 URL 格式一致,策略则丢弃所有未匹配的查询参数。
<!-- Assuming incoming request is /get?a=b&c=d and operation template is set to /get?a={b} -->
<policies>
<inbound>
<base />
<rewrite-uri template="/put" copy-unmatched-params="false" />
</inbound>
<outbound>
<base />
</outbound>
</policies>
<!-- Resulting URL will be /put -->
示例4:在模板中使用策略表达
在下面的例子中,策略使用模板中的表达式来构造向后端的请求。
<policies>
<inbound>
<base />
<set-variable name="apiVersion" value="/v3" />
<rewrite-uri template="@("/api" + context.Variables["apiVersion"] + context.Request.Url.Path)" />
</inbound>
</policies>
相关策略
相关内容
有关使用策略的详细信息,请参阅:
- 教程:转换和保护 API
- 策略参考,其中提供了策略语句及其设置的完整列表
- 策略表达式
- 设置或编辑策略
- 重复使用策略配置
- 策略片段存储库
- 策略操场存储库
- Azure API 管理策略工具包