IIS URL Rewrite Rules

2019-04-28 14:39发布

问题:

I have a AngularJS application that utilizes URL Rewriting for linking. My rewrite rule looks like :

<rewrite>
<rules> 
  <rule name="MainRule" 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_FILENAME}" matchType="Pattern" pattern="^api/(.*)" negate="false" />
    </conditions>
    <action type="Rewrite" url="Default.cshtml" />
  </rule>
</rules>

I found this solution on SO: How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode? and made one modification to allow my API to pass through.

Essentially, I want to redirect all my requests to Default.cshtml EXCEPT calls to my Web API. This works GREAT when I'm I load the app on the base URL like: localhost/myapp. However, if I reload the page on a angular route like: localhost/myapp/dashboard it fails saying:

<Error><Message>No HTTP resource was found that matches the request URI 'http://localhost/myapp/dashboard'.</Message>
<MessageDetail>No type was found that matches the controller named 'dashboard'.</MessageDetail></Error>

I have a work around where I did:

 <rewrite>
  <rules>
    <rule name="Default" stopProcessing="true">
      <match url="^(?!lib|api|dist|assets|app/|bower|common|main|signalr|templates|bower_components/).*" />
      <action type="Rewrite" url="Default.cshtml" />
    </rule>
  </rules>
</rewrite>

and it worked fine. Any ideas how I can utilize a cleaner solution above and still accomplish the rewrite?

回答1:

I need to change the pattern and change {REQUEST_FILE} to {REQUEST_URI} in a couple of places. See my demo here:

<rewrite>
  <rules>
    <rule name="MainRule" 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}" matchType="Pattern" pattern="api/(.*)" negate="true" />
        <add input="{REQUEST_URI}" matchType="Pattern" pattern="signalr/(.*)" negate="true" />
      </conditions>
      <action type="Rewrite" url="Default.cshtml" />
    </rule>
  </rules>
</rewrite>