Angular 4 Reverse Proxy on Azure

When you are deploying a modern SPA (Single Page Application) in Azure where your API’s are using a different host than your SPA application, you run into an issue with CORS (cross-origin resource sharing).  Simply put, your browser that is rendering your application from one host cannot make an AJAX request to an API on a different host for security reasons.  When you are deploying to IIS server on premises, a good solution is to use the URL Rewrite and Application Request Routing features built into IIS.

The same kind of configuration can be achieved with a web site hosted in Azure Web Sites.  Any site hosted in Azure Web Sites has URL Rewrite and ARR enabled.  However the proxy functionality is disabled by default in ARR. To enable that we will use the Azure Site Extension XDT transform which will modify the applicationHost.config file for our site and will enable proxy features.

Start by creating a file named applicationHost.xdt with the following XML and upload it to the root of your web site.

<?xml version="1.0"?>
<configuration xmlns:xdt="">
        <proxy xdt:Transform="InsertIfMissing" enabled="true" preserveHostHeader="false"           reverseRewriteHostInResponseHeaders="false" />

Next we will modify our web.config file with some routing rules:

    <rule name="ProxyRule" stopProcessing="true">
      <match url="^api/(.*)" />
      <action type="Rewrite" url="https://[your api host]/{R:0}" />

So now within your SPA application, any request made to https:[your spa host]/api/… will now be re-routed to the host configured in the rewrite rule. This rule that you have configured is the same rule you would use if you were deploying in IIS on premises with ARR.

If your site also uses ASP.NET MVC. When MVC is enabled on the web site used as a proxy then the MVC Router intercepts all the requests so they are not processed by ARR. So instead of request being forwarded to a destination server you get HTTP 404 – File Not Found error.

In order to fix this you’ll need to exclude the proxy route from the MVC routes by adding the following code to you MVC application: