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

Angular12部署后访问根路径报403如何配置自动跳转至/home路径

解决方案

你遇到的403错误本质是单页应用客户端路由和服务器路径匹配冲突导致,服务器默认会把根路径请求当做访问实际目录,找不到对应默认文件就抛出403,按以下三步配置即可解决:

  1. 调整Angular路由重定向规则
    把原空路径路由修改为强制重定向到home,需加上pathMatch: 'full'避免规则全局匹配所有路由:
const routes: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full', canActivate: [AuthGuard] },
    { path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
    { path: 'login', component: LoginComponent },
    // 应用其余路由保持不变
];

@NgModule({
    imports: [RouterModule.forRoot(routes, { relativeLinkResolution: 'legacy' })],
    exports: [RouterModule]
})
export class AppRoutingModule { }
  1. 配置子目录部署的base路径
    因为应用部署在/MyApplicationFolder/子目录下,打包时需要指定对应base-href参数,避免资源路径加载错误:
    ng build --prod --base-href /MyApplicationFolder/
    也可以直接修改项目index.html中的base标签为:<base href="/MyApplicationFolder/">

  2. 配置IIS服务器重写规则(Web Api2默认部署在IIS)
    在站点根目录添加web.config文件,将所有非静态文件、非Api接口的请求全部重定向到Angular的入口文件index.html,同时配置默认文档为index.html:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <defaultDocument>
      <files>
        <clear />
        <add value="index.html" />
      </files>
    </defaultDocument>
    <rewrite>
      <rules>
        <rule name="Angular SPA 路由支持" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <!-- 排除Web Api接口请求,不参与重写 -->
            <add input="{REQUEST_URI}" pattern="^/MyApplicationFolder/api" negate="true" />
          </conditions>
          <action type="Rewrite" url="/MyApplicationFolder/index.html" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

配置完成后重启IIS站点即可生效,用户访问根路径时会自动重定向到/MyApplicationFolder/home,未登录状态下AuthGuard也会正常跳转到登录页。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:06:03