React Router本地正常但Azure生产环境返回404问题求助
React路由部署Azure后404问题解决办法
一、核心原因
React的BrowserRouter采用客户端路由机制,当直接在地址栏输入路由路径(如/products)或刷新页面时,Azure服务器会尝试寻找对应物理路径的文件,找不到则返回404。本地开发时因webpack-dev-server自带路由回退配置,所以不会出现该问题。
二、解决方案
1. 修复Navbar路由跳转方式(推荐)
当前Navbar使用原生href会触发整页跳转,需替换为React Router的Link组件,确保客户端路由跳转:
import React from 'react'; import Navbar from 'react-bootstrap/Navbar'; import Nav from 'react-bootstrap/Nav'; import { Link } from 'react-router-dom'; const NavigationBar = () => { return ( <Navbar bg="dark" variant="dark"> <Navbar.Brand as={Link} to="/">Onboarding App</Navbar.Brand> <Nav className="mr-auto"> <Nav.Link as={Link} to="/customers">Customers</Nav.Link> <Nav.Link as={Link} to="/products">Products</Nav.Link> <Nav.Link as={Link} to="/stores">Stores</Nav.Link> <Nav.Link as={Link} to="/sales">Sales</Nav.Link> </Nav> </Navbar> ); }; export default NavigationBar;
2. .NET Core后端配置SPA回退路由
若为.NET Core与React同项目部署,在Program.cs(.NET 6+)中添加SPA回退配置,让所有客户端路由指向index.html:
var builder = WebApplication.CreateBuilder(args); // 其他服务配置... builder.Services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; // 根据实际React项目路径调整 }); var app = builder.Build(); // 其他中间件配置(静态文件、认证等)... app.UseSpaStaticFiles(); app.UseRouting(); // API路由等配置... app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; if (app.Environment.IsDevelopment()) { spa.UseReactDevelopmentServer(npmScript: "start"); } // 配置路由回退,禁止缓存index.html spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions { OnPrepareResponse = ctx => { ctx.Context.Response.Headers.Append("Cache-Control", "no-cache, no-store, must-revalidate"); } }; }); app.Run();
3. 单独部署React静态文件的Azure配置
若单独部署React的build文件夹到Azure App Service,需在build根目录添加web.config配置IIS URL重写规则:
创建web.config放在React项目的public文件夹(build时会自动复制到build目录):
<?xml version="1.0" encoding="UTF-8"?> <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" /> <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" /> <!-- 排除API路由 --> </conditions> <action type="Rewrite" url="/index.html" /> </rule> </rules> </rewrite> <staticContent> <mimeMap fileExtension=".json" mimeType="application/json" /> <mimeMap fileExtension=".js" mimeType="application/javascript" /> <mimeMap fileExtension=".css" mimeType="text/css" /> </staticContent> </system.webServer> </configuration>
三、验证步骤
- 应用配置后重新构建React项目:
npm run build - 重新部署到Azure App Service
- 测试直接访问路由路径或刷新页面,确认404问题解决
内容的提问来源于stack exchange,提问作者Yugraaj Sandhu
相关产品推荐
相关产品推荐

