在IIS单站点部署React+NET7 API:解决index.html 404问题
解决IIS单站点托管React与.NET7 API的index.html 404问题
问题背景
站点根目录结构如下:
- index.html
- 其他js/css静态资源文件
- api/my-app.exe(api子目录包含所有.NET API二进制文件)
目前/api/status健康检查接口可正常返回200,但访问/index.html时出现404错误。
解决方案
需要调整web.config中的handler匹配规则、ASP.NET Core进程路径,并添加正确的URL重写规则,具体如下:
1. 调整ASP.NET Core Handler的路径匹配
原handler的path="*"会拦截所有请求(包括静态文件),导致IIS无法直接返回index.html。修改为仅匹配api/*开头的请求,让静态文件由IIS默认处理:
<add name="aspNetCore" path="api/*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
2. 修正ASP.NET Core进程路径配置
原配置中processPath和arguments的路径格式错误,且无需手动指定dll(exe会自动加载同目录的对应dll),修正后:
<aspNetCore processPath=".\api\my-app.exe" stdoutLogEnabled="true" stdoutLogFile=".\iis-logs\" hostingModel="OutOfProcess" />
3. 添加URL重写规则
需要两条规则:
- 优先放行/api开头的API请求
- 对于非API请求,如果请求的文件/目录不存在,重写到index.html(适配React路由的单页应用特性)
完整web.config配置
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="aspNetCore" path="api/*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" /> </handlers> <aspNetCore processPath=".\api\my-app.exe" stdoutLogEnabled="true" stdoutLogFile=".\iis-logs\" hostingModel="OutOfProcess" /> <directoryBrowse enabled="false" /> <httpErrors errorMode="DetailedLocalOnly" existingResponse="Auto" /> <rewrite> <rules> <clear /> <!-- 放行所有API请求,交给ASP.NET Core处理 --> <rule name="API Requests" stopProcessing="true"> <match url="^api/(.*)" /> <action type="None" /> </rule> <!-- 非API请求,若文件/目录不存在则重写到index.html --> <rule name="React SPA 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>
说明
- 第一条规则确保所有/api开头的请求直接交给ASP.NET Core模块处理,不会被重写
- 第二条规则针对单页应用:当请求的不是实际存在的文件或目录时,重写到index.html,既保证React路由正常工作,也不影响静态文件的直接访问
内容的提问来源于stack exchange,提问作者Jacek
相关产品推荐
相关产品推荐

