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

Azure App Service部署React+Vite应用刷新页面出现404问题求助

解决Azure App Service中React+Vite应用刷新路由404问题

核心原因

Azure App Service默认作为静态文件服务器运行,不会识别React Router的前端路由规则。当直接刷新非根路径页面时,服务器会尝试寻找对应物理文件,找不到就返回404。你之前添加的_redirects文件是Netlify/Vercel等平台的专属配置,Azure App Service不支持该文件。

针对性解决方案

1. Windows环境的Azure App Service

在项目根目录创建web.config文件,添加IIS重写规则:

<?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>

该配置会将所有非文件、非目录的请求重定向到index.html,交给React Router处理。

2. Linux环境的Azure App Service

方式一:Nginx配置

在项目根目录创建.config文件夹,内部新建nginx.conf文件:

server {
    listen        8080;
    server_name   localhost;
    root          /home/site/wwwroot;
    index         index.html;

    # 前端路由重写规则
    location / {
        try_files $uri $uri/ /index.html;
    }

    # 保留API路由(按需修改)
    location /api {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

方式二:静态站点配置文件

在项目根目录创建staticwebapp.config.json文件:

{
  "navigationFallback": {
    "rewrite": "/index.html",
    "exclude": ["/images/*.{png,jpg,gif}", "/css/*"]
  }
}

3. 验证步骤

  • 将对应环境的配置文件添加到项目根目录
  • 重新执行npm run build构建项目
  • 重新部署到Azure App Service,刷新路由页面测试

内容的提问来源于stack exchange,提问作者Laura Díaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 16:49:53