同一域名下Angular与API部署的web.config路由配置修改咨询
调整web.config路由规则实现API路径迁移
要把原api.app.com的API服务迁移到www.app.com/api路径,你需要调整web.config里的重写规则,优先处理/api开头的请求,剩下的非文件、非目录请求再交给Angular应用的index.html。以下是修改后的完整配置:
<configuration> <system.webServer> <rewrite> <rules> <!-- 优先匹配API请求,转发到实际API服务端点 --> <rule name="API Routes" stopProcessing="true"> <!-- 匹配所有以/api开头的请求 --> <match url="^api/(.*)" /> <!-- 将请求转发到API服务的实际处理路径,这里假设API后端入口是/api/{匹配到的路径} --> <!-- 如果你的API是部署在同服务器的其他目录,比如backend/api,可修改为url="backend/api/{R:1}" --> <action type="Rewrite" url="/api/{R:1}" /> <!-- 如果需要临时反向代理到原api.app.com,可改用以下配置: <action type="Rewrite" url="https://api.app.com/{R:1}" /> <serverVariables> <set name="HTTP_X_ORIGINAL_HOST" value="{HTTP_HOST}" /> </serverVariables> --> </rule> <!-- Angular路由规则:处理非文件、非目录、非API的请求 --> <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" /> <!-- 保留这个条件,确保/api开头的请求不会被Angular规则处理 --> <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" /> </conditions> <action type="Rewrite" url="/" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
关键修改说明:
- API Routes规则:新增了完整的匹配逻辑,优先捕获所有
/api/xxx格式的请求,将其转发到实际的API服务处理路径。如果是临时过渡需要反向代理到原api.app.com,可注释掉默认的action,改用注释里的反向代理配置。 - Angular Routes规则:保留了原有的
^/(api)排除条件,确保API请求不会被误转发到Angular的index.html。
注意事项:
- 确保你的API服务已经部署到
www.app.com对应的服务器上,且能处理/api路径的请求。 - 如果使用反向代理,需要在IIS中启用**Application Request Routing (ARR)**模块,并开启反向代理功能。
内容的提问来源于stack exchange,提问作者rst
相关产品推荐
相关产品推荐

