azureazure-api-managementapim

Rewriting URLs for Azure APIM Polices


I want to allow public form URL to send without v2 (version identifier) then add it back in for the backend, the v2 is always before the operations and parameters for all endpoints, how can I use the <rewrite-uri template=""/> to add the v2 back in to allow user to send URL without v2?

So public form URL will be https://bla.bla.com/myapi/Polices/12/14 or https://bla.bla.com/myapi/Producers/12. I need to rewrite to https://bla.bla.com/myapi/v2/Producers/12 and https://bla.bla.com/myapi/v2/Polices/12/14.

I don't find the documentation around rewrite helpful for my scenario as the example seems to be writing the Policy at an operation level knowing the parameters that will be passed in.

I've tried many different things e.g.

<rewrite-uri template="@(context.Request.OriginalUrl.Path.Replace("/myapi/","myapi/v2/"))" />

but nothing seems to work. How can I rewrite my URLs?


Solution

  • Let's say the base URL of the API in your API Management service is https://your-api-management.azure-api.net/myapi, and you need all requests to be redirected to https://bla.bla.com/myapi/v2. Can't you just achieve it by setting the Web service URL to https://bla.bla.com/myapi/v2 and using an operation with the /* Frontend URL?

    At least the following configuration works for me:

    API settings

    Frontend

    Then requests to https://your-api-management.azure-api.net/myapi/Polices/12/14 would be redirected to https://bla.bla.com/myapi/v2/Polices/12/14; requests to https://your-api-management.azure-api.net/myapi/Producers/12 would be redirected to https://bla.bla.com/myapi/v2/Producers/12, etc.

    Or is this not what you are trying to achieve?

    I have just tested this setup with the following policy to ensure that the backend URL was correct ā€“

    <on-error>
        <set-header name="Backend-URL" exists-action="override">
            <value>@(context.Request.Url.ToString())</value>
        </set-header>
        <base />
    </on-error>
    

    ā€“ and the result was as expected:

    Test