在IIS上托管的Angular 2:HTTP错误404

Hus*_*man 13 iis http-status-code-404 angular2-routing angular

我有一个简单的应用程序,其中一个组件需要来自url的某些参数.应用程序中只有一条路线:

const appRoutes: Routes = 
                       path: 'hero/:userId/:languageId',component: HeroWidgetComponent }];
Run Code Online (Sandbox Code Playgroud)

在Index.html中,我在标题中有这个 <base href="/">

我正在使用webpack,并且在浏览url时,应用程序在开发环境中运行良好:http://localhost:4000/hero/1/1.

但是,在构建用于生产的应用程序并获取分发文件时,请在IIS上托管该应用程序.尝试浏览同一个网址时出现以下错误:

HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Run Code Online (Sandbox Code Playgroud)

如果我删除所有路由并只http:localhost:4200在IIS上浏览:该应用程序工作正常.

Hus*_*man 34

我们必须通过添加重写规则使IIS回退到index.html.

第1步: 安装IIS URL重写模块

第2步: 向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>
Run Code Online (Sandbox Code Playgroud)

  • @mapussah,可能是因为这个模块已经安装了。 (2认同)
  • 如何在 IIS 网站配置下进行此更改,而不必使用 web.config 文件 (2认同)

oga*_*sev 6

第 3将 web.config 链接添加到 angular.json:(因为在 ng build 之后它会被跳过)

"architect": {
                "build": {
                    "builder": "@angular-devkit/build-angular:browser",
                    "options": {
                         ..........
                        "assets": [
                            "src/favicon.ico",
                            "src/assets",
                            **"src/web.config"**
                        ]
Run Code Online (Sandbox Code Playgroud)


reg*_*gik 5

不安装 IIS URL 重写

正如@tftd 在问题评论中所解释的那样,IIS 需要知道当找不到匹配的文件或文件夹时如何处理请求。

您可以将 IIS 配置为在请求带有路径和/或参数(也称为深层链接)的路由时返回index.html 。

在 IIS 中手动

  1. 在 IIS 管理器中选择您的站点
  2. 打开IIS部分中的错误页面图标
  3. 打开状态代码404列表项
  4. 选择在此站点上执行 URL单选按钮
  5. 输入您的 SPA 根路径,例如:'/index.html'
  6. 单击“确定” 编辑自定义错误

无需重新启动应用程序池,只需浏览到您的深层链接即可。服务器将以状态代码 200 进行响应。(2021 年在带有 IIS 10 的 Windows Server 2016 上测试)。

如果您的 SPA 未植根于/index.html,请输入您的应用程序在步骤 5 中植根的文件夹或文件。

上述手动过程添加或更改web.config的httpErrors部分:

<configuration>
    <system.webServer>
        <httpErrors>
            <remove statusCode="404" subStatusCode="-1" />
            <error statusCode="404" prefixLanguageFilePath="" path="/index.html" responseMode="ExecuteURL" />
        </httpErrors>
    </system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)

为了避免在下次部署后丢失此更改,请确保您的发布管道在web.config中保留httpErrors部分,如上面所示。

这适用于AngularReact应用程序。