azureazure-api-managementibm-api-management

How do I enforce a URL redirect when API URL suffix is not passed for my API Management


I have looked into the Rewrite URL for azure APIM but I don't know if this is the right approach as it looks like its more for the operations

I have an API Management instance (https://my-apim.azure-api.net) with 2 APIs:

AP1 1:- https://my-apim.azure-api.net/api1

AP1 2:- https://my-apim.azure-api.net/api2

I want to implement a case where the APIM redirects to the login page (e.g https://www.mywebsite.com/login) if my APIM is called without the API suffix (e.g. "/api2").

How would I go about this?


Solution

  • "All APIs" policy is executed for every request APIM receives. on-error section, among other cases, is executed if received request is not matched with any operation registered in APIM. See this doc on how to handle errors like 404 and others: https://learn.microsoft.com/en-us/azure/api-management/api-management-error-handling-policies, but in short, adding something like below into on-error at All APIs scope should do the trick:

    <choose>
      <when condition="@(context.LastError.Reason == "OperationNotFound")">
        <return-response>
          <set-status code="307" reason="Temporary Redirect"/>
          <set-header name="Location" exists-action="override">
            <value>https://www.mywebsite.com/login</value>
          </set-header>
        </return-response>
      </when>
    </choose>
    

    You can implement additional checks to specifically target scenario when suffix is not provided, but above will cover all cases when URI in does not match any operation.