在IIS中托管多个Angular应用并配置URL重写的方法
前置准备
- 先安装IIS的「URL 重写模块」和「应用程序请求路由 (ARR)」,两个组件安装完成后重启IIS管理器。
- 确保
localhost:3000/App2/employees可以直接正常访问,App2的Angular项目配置正确的base href,避免后续静态资源加载失败。 - 开启ARR代理功能:打开IIS管理器根节点,找到「应用程序请求路由缓存」,点击右侧操作栏的「代理设置」,勾选「启用代理」后保存配置,重启IIS。
配置URL重写规则
你可以直接在IIS管理器图形界面配置,也可以直接修改localhost:80对应站点根目录的web.config文件,添加对应规则:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <!-- App2反向代理规则 --> <rule name="Proxy App2 to localhost:3000" stopProcessing="true"> <match url="^App2(/.*)?$" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="http://localhost:3000/App2/employees{R:1}" appendQueryString="true" /> </rule> <!-- App1的Angular单页应用路由回退规则,保留原有访问能力 --> <rule name="App1 SPA Route Fallback" stopProcessing="true"> <match url="^App1(/.*)?$" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="/App1/heroes/index.html" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
额外配置校验
- App2项目构建时需要指定base href为
/App2/,构建命令为ng build --base-href /App2/,保证静态资源路径匹配。 - 配置完成后清除浏览器缓存再测试,避免缓存的旧重定向规则影响校验结果。
内容的提问来源于stack exchange,提问作者Argha Ray
相关产品推荐
相关产品推荐

