You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

部署在Azure App Service的React子路由直接访问失效求助

问题原因

你遇到的是单页应用(SPA)部署到Azure App Service的典型路由问题:React的BrowserRouter使用HTML5 History模式,前端导航时通过JS切换路由,不会向服务器发送新请求;但直接在地址栏输入子路由(如/about)时,浏览器会向Azure的Web服务器发起请求,服务器会尝试寻找对应路径的物理文件,找不到就返回404错误。本地开发时,Create React App的内置服务器已经处理了这种路由转发,所以没有问题。

解决方案

需要在Azure App Service中配置URL重写规则,让所有非静态资源的请求都转发到index.html,由React Router处理路由。具体步骤:

  1. 在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" />
            <!-- 如果你的应用有API接口,取消下面注释以排除API路径,避免被转发 -->
            <!-- <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" /> -->
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>
  1. 重新打包你的React应用(运行npm run build),将build目录的内容重新部署到Azure App Service。

这样配置后,当用户直接访问子路由时,服务器会返回index.html,React Router就能正确加载对应的页面组件了。

内容的提问来源于stack exchange,提问作者K.Z

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 14:32:23