Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IIS Url rewrite rule for Angular SPA + WebApi

Tags:

iis-7

rewrite

I have a SPA + WebAPI application, they are both in the same project. I only want the WebAPI application to process requests from the directory "api". So anything under api will be handled by the server, everything else will be handled by the Angular SPA.

I currently have

   <rewrite>
      <rules>
        <rule name="AngularJS" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>

This works OK except when I go to the URL

http://localhost/customers/2 (which loads the doc but all resources are coming in with the wrong mime type I have concluded its because of the redirect rules above)

the URL http://localhost/customers works fine will be routed by my SPA app

How do I get everything to be redirected to my SPA except for the requests that come under the API directory?

like image 450
Paul Avatar asked Dec 11 '14 02:12

Paul


People also ask

What is rewrite URL in IIS?

About the URL Rewrite module The Microsoft URL Rewrite Module 2.0 for IIS 7 and above enables IIS administrators to create powerful customized rules to map request URLs to friendly URLs that are easier for users to remember and easier for search engines to find.


1 Answers

I do this with two rules. One to "whitelist" the server-side controllers I want to go to asp.net, which includes /api but also the authentication stuff under /Account and /Manage. The next sends everything else to angular unless it's a file or folder, much like what you already have.

    <rule name="API Rule" stopProcessing="true">
      <match url="^(api|account|manage)(.*)$" />
      <action type="None" />
    </rule>
    <rule name="Angular Rule" stopProcessing="true">
      <match url="(.*)" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Rewrite" url="/" />
    </rule>

Try it this way, but feel free to remove "|account|manage" if you don't want those requests going to the server.

To see my entire ruleset, check out this question I have posted, where I handle HTTPS and canonical hostnames as well.

like image 120
Chris Avatar answered Sep 20 '22 16:09

Chris