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

Angular9应用部署IIS遇403访问拒绝问题求助

解决Angular 9部署IIS后访问根路径403的问题

你的问题核心是IIS未将目录请求默认指向index.html,同时缺少正确的SPA路由重写规则,导致直接访问https://localhost/xaportal时触发403错误。以下是针对性的解决方案:

1. 配置正确的web.config文件

将以下配置文件放在xaportal目录的根目录下,这是解决IIS上SPA部署问题的关键:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <!-- 设置默认文档,让IIS访问目录时自动加载index.html -->
    <defaultDocument enabled="true">
      <files>
        <add value="index.html" />
      </files>
    </defaultDocument>

    <!-- URL重写规则,处理Angular SPA路由的刷新问题 -->
    <rewrite>
      <rules>
        <rule name="Angular Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <!-- 排除实际存在的文件(如js、css、图片等) -->
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <!-- 排除实际存在的目录 -->
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <!-- 如果项目有API接口,添加此规则排除API路径,避免被重写 -->
            <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
          </conditions>
          <!-- 将所有符合条件的请求重写到index.html -->
          <action type="Rewrite" url="/xaportal/index.html" />
        </rule>
      </rules>
    </rewrite>

    <!-- 添加Angular静态资源需要的MIME类型,避免加载失败 -->
    <staticContent>
      <mimeMap fileExtension=".json" mimeType="application/json" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
      <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
    </staticContent>
  </system.webServer>
</configuration>

2. 确认IIS已安装URL重写模块

如果之前配置重写规则未生效,大概率是IIS未安装URL Rewrite模块:

  • 打开IIS管理器,查看左侧“模块”列表,确认是否存在“URL Rewrite”;
  • 若未安装,需安装该模块(可通过IIS管理器的“Web平台安装程序”搜索下载)。

3. 检查目录权限与站点配置

  • 确保xaportal目录的权限已授予IIS_IUSRS和IUSR用户读取权限;
  • 确认IIS站点的物理路径正确指向xaportal所在的目录。

关于Angular路由的补充说明

Angular的客户端路由本身不需要设置重定向到index.html,因为index.html是应用的入口文件。如果需要在加载应用后默认跳转到某个组件,可在app-routing.module.ts中配置默认路由:

const routes: Routes = [
  // 根路径重定向到home组件
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  // 其他路由配置
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

此配置解决的是应用加载后的客户端路由跳转,而非访问根路径时的403问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:52:59