You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 14部署为IIS网站后出现404错误的排查求助

Angular 14部署IIS出现404问题排查与解决

问题场景

我创建了一个基础Angular 14应用,部署到IIS时遇到404错误,相关信息如下:

应用代码

  • app.component代码:
// in app.component
<h1>THIS IS ANGULAR TEST APP</h1>

// test of paths
<img src="../resources/Samolot.jpg" alt="asd">
<img src="/src/resources/icon - Copy.png" alt="asd">
<img src="./../assets/icon - Copy.png" alt="asd">
<img src="./../assets/Samolot.jpg" alt="asd" width="400px" height="400px">

<router-outlet></router-outlet>
  • TestComponent代码:
<h1>This is test component</h1>
  • 路由配置:
const routes: Routes = [
  { path: "another", component: TestComponent },
];

部署操作

  1. 执行构建命令:ng build --configuration production --base-href /testapp/
  2. 在IIS中通过AddWebsite创建站点,名称设为testapp并指定物理路径
  3. 已安装URL Rewrite模块
  4. 添加的web.config内容:
<?xml version="1.0" encoding="utf-8"?>
<configuration>

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Angular 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="/testapp/" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

</configuration>

异常表现

访问http://localhost:4200/testapp时出现404错误,但以下两种场景能正常运行:

  • 执行ng build --configuration production(不加--base-href参数),同时修改web.config的action为"/"
  • 在IIS中选择AddApplication而非AddWebsite,使用原配置

问题原因与解决方案

核心原因:独立站点与子应用的路径映射差异

当使用AddWebsite创建独立站点时,该站点在IIS中本身就是根路径(/),但你通过--base-href /testapp/让Angular把所有资源、路由的前缀都设为/testapp/,这就导致了路径冲突:
Angular构建后会请求/testapp/xxx这类路径,但IIS会在站点的物理目录下寻找testapp子目录(实际不存在),最终返回404。

而用AddApplication时,它是作为主站点的子应用存在,路径本身就是/testapp,和--base-href的配置完全匹配,因此能正常工作。

解决方案

方案1:调整构建命令与web.config(推荐)

因为是独立站点,base-href应该设为根路径:

ng build --configuration production --base-href /

同时修改web.config中的action为根路径:

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

修改后直接访问http://localhost:4200(对应站点绑定的端口)即可正常打开应用,路由/another也能正常跳转。

方案2:调整IIS站点绑定规则(不推荐)

如果坚持要保留--base-href /testapp/,可以将该站点作为现有主站点的虚拟子路径,但这种方式会增加配置复杂度,不如方案1直接高效。

额外提示:规范静态资源路径

你app.component中的图片路径存在不规范问题,Angular项目的静态资源应统一放在assets目录下,正确的引用方式为:

<img src="assets/Samolot.jpg" alt="asd">
<img src="assets/icon - Copy.png" alt="asd">

这样构建后资源路径会自动适配base-href配置,避免出现资源加载失败的问题。


内容的提问来源于stack exchange,提问作者ruddnisrus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 21:36:00