create-react-app部署到Azure后报404资源加载错误本地运行正常如何解决
Create React App部署Azure后404错误解决方案
你遇到的报错信息如下:
Failed to load resource: the server responded with a status of 404 (The requested content does not exist.)

以下是对应排查和解决步骤:
1 客户端路由配置缺失(最高发原因)
Create React App本地开发时,webpack dev server会自动将所有路由请求回退到index.html,适配BrowserRouter的客户端路由逻辑,但Azure服务默认没有该配置,直接访问非根路径或者刷新页面就会触发404。
根据你的部署类型选择对应配置:
- Azure静态Web应用部署:在项目根目录新增
staticwebapp.config.json文件,配置回退规则:
{ "navigationFallback": { "rewrite": "index.html", "exclude": ["/static/**/*.{png,jpg,gif,css,js,svg}"] } }
- Azure App Service Windows环境部署:在项目public目录下新增
web.config文件,配置URL重写规则:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="React SPA路由回退" 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>
- Azure App Service Linux环境部署:如果使用Nginx作为服务容器,需要修改Nginx配置,添加
try_files $uri $uri/ /index.html;规则,再重新打包部署。
2 静态资源路径配置错误
检查package.json文件中的homepage字段:
- 应用部署在域名根路径时,配置为
"homepage": "."或者留空 - 应用部署在子路径时,配置为
"homepage": "https://你的Azure站点域名/子路径名称"
配置错误会导致打包后生成的js、css等静态资源引用路径错误,触发资源404。
3 文件名大小写不匹配
本地Windows、macOS系统的文件系统默认大小写不敏感,而Azure Linux环境大小写敏感,如果代码中引用文件的路径大小写和实际文件名不一致,本地运行正常但部署后就会404。需要逐一检查资源引用路径的大小写和实际文件保持一致。
4 部署文件不完整
登录Azure控制台进入对应应用的文件管理器,确认build目录下的所有文件都已正确上传,尤其是index.html和static文件夹下的资源文件没有缺失。
内容的提问来源于stack exchange,提问作者ashok.kk
相关产品推荐
相关产品推荐

