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

如何在IIS中部署Angular根应用及子应用并解决URL Rewrite错误?

IIS部署Angular根应用与子应用(/app1)的配置方案

一、Angular子应用预构建配置

  • 构建子应用时必须指定base-href参数,确保资源路径指向子应用路径:
    ng build --base-href /app1/
    
    该命令会将子应用的所有静态资源、路由基准路径绑定到/app1/,避免请求根应用的资源文件。

二、IIS虚拟目录设置

  1. 打开IIS管理器,定位到根网站(对应www.example.com的站点)。
  2. 右键根网站,选择添加虚拟目录:
    • 别名填写app1,物理路径指向子应用构建后生成的dist/子应用文件夹路径。
  3. 给虚拟目录的IIS_IUSRS用户分配读取权限,确保静态资源可正常访问。
  4. 虚拟目录应用池选择与根应用一致的池即可,注意应用池需设置为无托管代码(Angular为静态单页应用)。

三、URL Rewrite规则配置(核心解决路由冲突)

1. 根应用web.config修改

根应用的路由重写规则需要排除/app1/路径,避免子应用请求被错误重写到根应用的index.html。修改根网站根目录下的web.config,添加排除条件:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Angular Root Routes" 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="^/app1/" negate="true" />
          </conditions>
          <action type="Rewrite" url="/index.html" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

2. 子应用web.config配置

在子应用的dist目录下创建(或修改)web.config,配置自身路由重写规则,确保子应用路由请求重写到自己的index.html:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Angular SubApp 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>
          <!-- 重写路径指向子应用的index.html -->
          <action type="Rewrite" url="/app1/index.html" />
        </rule>
      </rules>
    </rewrite>
    <!-- 可选:添加缺失MIME类型,避免json、woff2等静态资源加载失败 -->
    <staticContent>
      <remove fileExtension=".json" />
      <mimeMap fileExtension=".json" mimeType="application/json" />
      <remove fileExtension=".woff2" />
      <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
    </staticContent>
  </system.webServer>
</configuration>

四、验证配置

  1. 重启IIS站点,访问www.example.com确认根应用正常运行。
  2. 访问www.example.com/app1确认子应用加载正常,再测试子应用路由(如www.example.com/app1/user),检查是否无404错误且路由跳转正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 09:15:55