如何在IIS中搭建并配置Angular 12子应用?
解决方案
- 处理路径空格问题:IIS中子应用别名避免使用空格,建议将
child cool app重命名为child-cool-app这类无空格的名称,可规避大量路径解析异常;如果必须保留空格,执行ng build命令时需要给base-href参数值加英文双引号包裹,同时注意:因子应用嵌套在Cool App父应用下,不是直接挂载在站点根目录,所以base-href的值需要写完整的「父应用路径+子应用路径」,不能只写子应用的路径,示例如下:
ng build --configuration production --base-href "/cool app/child cool app/"
- 配置正确的base标签:index.html中的base标签和build参数保持一致即可,若已调整为无空格路径,对应修改为
<base href="/cool-app/child-cool-app/">即可。 - 子应用单独配置IIS URL重写规则:父应用的重写规则不会自动继承给子应用,需要在子应用的打包输出根目录下新增web.config文件,添加Angular SPA所需的重写规则,内容如下:
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <staticContent> <mimeMap fileExtension=".json" mimeType="application/json" /> <mimeMap fileExtension=".woff" mimeType="font/woff" /> <mimeMap fileExtension=".woff2" mimeType="font/woff2" /> </staticContent> <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="./index.html" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
需提前确认IIS已经安装了URL重写模块,否则上述规则不会生效。
- 配置.NET 5的应用路径:在项目的Startup.cs或者Program.cs文件中,UseRouting方法之前添加UsePathBase配置,对应你的子应用完整路径:
app.UsePathBase("/cool app/child cool app/");
- 检查IIS基础配置:
- 确认子应用对应的应用程序池.NET CLR版本设置为「无托管代码」
- 确认子应用的物理路径已经给IIS_IUSRS用户分配了读取、执行权限
- 可临时移除父应用的重写规则测试子应用是否能正常访问,排查父应用规则拦截的可能
内容的提问来源于stack exchange,提问作者Mike Gmez
相关产品推荐
相关产品推荐

