Azure DevOps部署React应用至App Service访问返回404问题求助
问题根因及对应解决方案
1. 部署路径层级错误
你当前的构建流程会将React的构建产物存放在build目录下,若部署时将包含build目录的上层文件夹直接上传到App Service的wwwroot目录,站点根目录就找不到入口index.html文件,触发404。
修复方案:
调整「Deploy Azure App Service」任务的「包或文件夹」路径,直接选择构建产物中的build目录本身,确保build目录下的所有文件(包括index.html)直接部署到App Service的/home/site/wwwroot(Linux)或wwwroot(Windows)根目录,不要嵌套多余的build层级。
部署完成后可以通过App Service的Kudu高级工具查看站点根目录,确认index.html文件存在。
2. 单页应用路由回退规则缺失
React为客户端路由的单页应用,默认的App Service服务端配置不会将不存在的路径请求重定向到入口index.html,直接访问非根路径时就会返回404。
修复方案:
根据你的App Service运行环境选择对应配置:
- 若使用Windows托管环境:在React项目的
public目录下新增web.config文件,内容如下,重新构建部署即可:
<?xml version="1.0"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="React 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="/" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
- 若使用Linux托管环境:进入Azure门户对应App Service的配置页,在「设置>配置>常规设置>启动命令」中填入以下内容,保存后重启应用即可:
pm2 serve /home/site/wwwroot --no-daemon --spa
如果你的构建产物最终存放在站点根目录的build子目录下,将启动命令调整为:
pm2 serve /home/site/wwwroot/build --no-daemon --spa
内容的提问来源于stack exchange,提问作者AppSupportGuru1995
相关产品推荐
相关产品推荐

