Angular 2 Hosted on IIS: HTTP Error 404

2019-02-02 16:49发布

I have simple app with one component that expects certain parameters from url. there is only one route in the application:

const appRoutes: Routes = 
                       path: 'hero/:userId/:languageId',component: HeroWidgetComponent }];

In the Index.html, I have this in the header <base href="/">

I am using webpack and the application runs fine on development environment, when browsing the url: http://localhost:4000/hero/1/1.

However, when building the app for production and getting the distribution files, then hosting that on IIS. I get the following Error when trying to browse the same url:

HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

The application works fine if I remove all the routing and just browse: http:localhost:4200 on the IIS.

2条回答
劫难
2楼-- · 2019-02-02 17:27

If you are using an IIS application like myApp below your default web site (then the URL to your application should have the syntax http://localhost/myApp/my-angular-route), then you should try to modify the action to

<action type="Rewrite" url="/myApp/"/>;

Then it works for my environment without any problems.

Step by step instructions can be found here: https://blogs.msdn.microsoft.com/premier_developer/2017/06/14/tips-for-running-an-angular-app-in-iis/

查看更多
小情绪 Triste *
3楼-- · 2019-02-02 17:36

We have to make IIS fall back to index.html by adding a rewrite rule.

Step 1: Install IIS URL Rewrite Module

Step 2: Add a rewrite rule to web.config

   <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <system.webServer>
        <rewrite>
          <rules>
            <rule name="AngularJS Routes" 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>
          </rules>
        </rewrite>
      </system.webServer>
    </configuration>
查看更多
登录 后发表回答