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

使用Amplify托管Vite SPA时重定向出现GET错误求助

解决AWS Amplify部署Vite+React项目路由重定向崩溃问题

我近期用Amplify构建Vite+React项目,构建流程正常,但通过react-router-dom做页面重定向时,页面崩溃并抛出错误(截图:重定向错误截图)。

我的配置与项目结构

Amplify构建配置:

version: 1
frontend:
  phases:
    preBuild:
      commands:
        - npm ci
    build:
      commands:
        - npm run build --prod
  artifacts:
    baseDirectory: /dist
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*

构建后项目结构(Vite默认):

dist
|__assets
|
|__index.html

已尝试添加SPA自定义重定向规则 <\/^[^.]+$|\.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|ttf|map|json)$)([^.]+$)/>,但重定向时页面仍崩溃。


解决方案

  1. 修正Amplify重定向规则格式
    Amplify的重定向正则不需要转义开头斜杠,且必须指定目标地址为/index.html、类型为200 (Rewrite)。在Amplify控制台的Rewrites and redirects页面,更新规则为:
  • 源地址:</^[^.]+$|\.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|ttf|map|json)$)([^.]+$)/>
  • 目标地址:/index.html
  • 类型:200 (Rewrite)

之前的规则因多余转义导致匹配异常,无法正确将非静态资源请求导向index.html,引发路由加载失败。

  1. 检查Vite的base路径配置
    如果项目部署在子路径下(比如自定义域名的子目录),需在vite.config.js中设置正确的base值:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  base: '/' // 若部署路径为/my-app/,则改为'/my-app/'
})

错误的base路径会导致重定向后静态资源加载失败,进而引发页面崩溃。

  1. 确认react-router-dom路由模式
    确保使用BrowserRouter而非HashRouter(Amplify托管SPA推荐前者),路由配置示例:
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        {/* 其他路由配置 */}
      </Routes>
    </Router>
  );
}
  1. 重新触发构建部署
    修改规则和配置后,在Amplify控制台手动触发重新构建,确保新配置生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:30:43