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

部署在Azure的Create-React-App非首页刷新/输URL报404求助

解决Azure部署React应用后非首页刷新404的问题

以下是你可能遗漏的解决方法:

针对Azure App Service(IIS环境)

  • 确保web.config的位置和内容正确
    把正确的web.config放在项目的public文件夹下(不是项目根目录或手动添加在IIS),执行npm run 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>
      </system.webServer>
    </configuration>
    
  • 验证部署包内容
    确认部署到Azure的是build文件夹的完整内容,而非项目根目录。如果用自动化部署(如GitHub Actions),检查工作流中output_location是否设为build。

针对Azure Static Web Apps

  • 使用新版配置文件staticwebapp.config.json
    替代旧版的routes.json,在项目根目录创建staticwebapp.config.json,内容如下:
    {
      "navigationFallback": {
        "rewrite": "/index.html",
        "exclude": ["/images/*.{png,jpg,gif}", "/css/*", "/js/*"]
      }
    }
    
    该配置会将所有非静态资源的请求重定向到index.html,同时保留静态文件的正常访问。
  • 检查部署工作流配置
    确认GitHub Actions或Azure DevOps的工作流中,app_location指向React项目根目录,output_location设为build。

通用检查项

  • 确认应用部署路径
    如果应用部署在Azure的子路径下(如https://xxx.azurewebsites.net/my-app),需要在路由初始化时添加basename参数:
    const router = createBrowserRouter([
      // 你的路由配置
    ], {
      basename: '/my-app' // 替换为实际子路径
    });
    
  • 清除Azure缓存
    部署后在Azure门户对应服务中重启应用,或在静态Web Apps的「配置」-「缓存」中手动清除缓存,避免旧配置残留。

内容的提问来源于stack exchange,提问作者Khepf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 02:10:15