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

Nuxt2全静态构建路由在AWS Amplify中无法正常工作

Nuxt2 静态部署(SSR=true)在Amplify上的路由问题解决

问题根源

当设置ssr: true, target: static时,Nuxt会为每个路由预生成对应文件夹下的index.html(比如/about对应dist/about/index.html),但Amplify默认的静态资源路由规则不会自动将子路由请求映射到对应的index.html,导致导航或直接访问子路由时出现404,仅URL变化但页面无响应。

解决方案

1. 修改Amplify构建配置,添加路由重写规则

在项目根目录的amplify.yml(或现有构建配置文件)中添加redirects规则,让所有非静态资源的请求都指向/index.html,同时保留静态资源的直接访问:

version: 1
frontend:
  phases:
    preBuild:
      commands:
        - yarn install
    build:
      commands:
        - echo "HOSTNAME=$HOSTNAME" >> .env
        - yarn generate
  artifacts:
    baseDirectory: dist
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*
# 新增路由重写规则
redirects:
  - source: '</^[^.]+$|\.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|woff2|ttf|map|json)$)([^.]+$)/>'
    target: /index.html
    status: 200

这个规则会匹配所有不包含静态资源后缀的请求,将其重定向到index.html,让Nuxt的路由系统处理,同时确保CSS、JS等静态资源可以正常加载。

2. 确认Nuxt配置正确性

  • 若部署在子路径下,需设置router.base,比如部署在https://example.com/nuxt-app,则:
    // nuxt.config.js
    export default {
      router: {
        base: '/nuxt-app/'
      }
    }
    
  • 若存在动态路由(如/posts/:id),必须在generate.routes中预生成所有动态路由,否则Amplify无法找到对应静态HTML:
    // nuxt.config.js
    export default {
      ssr: true,
      target: 'static',
      generate: {
        routes: async () => {
          // 示例:从API获取动态路由列表
          const response = await fetch('https://your-api-domain.com/posts')
          const posts = await response.json()
          return posts.map(post => `/posts/${post.id}`)
        }
      }
    }
    

3. 验证效果

  • 本地使用npx serve dist启动服务器,测试路由导航和直接访问子路由是否正常
  • 重新部署到Amplify后,导航和直接访问子路由都会加载对应的预生成HTML,同时禁用JS时仍能看到完整页面内容,满足SEO需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:56:08