Angular12部署后访问根路径报403如何配置自动跳转至/home路径
解决方案
你遇到的403错误本质是单页应用客户端路由和服务器路径匹配冲突导致,服务器默认会把根路径请求当做访问实际目录,找不到对应默认文件就抛出403,按以下三步配置即可解决:
- 调整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 { }
配置子目录部署的base路径
因为应用部署在/MyApplicationFolder/子目录下,打包时需要指定对应base-href参数,避免资源路径加载错误:ng build --prod --base-href /MyApplicationFolder/
也可以直接修改项目index.html中的base标签为:<base href="/MyApplicationFolder/">配置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
相关产品推荐
相关产品推荐

