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

Vue3 SPA集成Amazon Cognito后Nginx与Vue Router路由异常求助

问题:Vue3 SPA集成Cognito登录后/callback路由Nginx报错

我开发了基于Vue3的前端单页应用(SPA),集成了Amazon Cognito认证功能。登录流程可正常完成,但登录后重定向至应用的/callback路径时出现异常,浏览器报错。查看Nginx错误日志发现如下报错:

2024/07/23 09:37:09 [error] 29#29: *9 open() "/usr/share/nginx/html/callback" failed (2: No such file or directory), client: 10.1.1.70, server: localhost, request: "GET /callback?code=22c784ca-4973-4268-96d4-735dba9ddf08 HTTP/1.1", host: "mask.mask.com", referrer: "https://mask.auth.mask.amazoncognito.com/"

我推测错误原因是Nginx尝试查找名为callback的静态文件,但原本预期Vue Router会处理该路由,将未找到的路径指向index.html。以下是我的Vue Router配置与Nginx配置,且已尝试修改Nginx配置但未解决问题,恳请告知原因及修复方法。

Vue Router配置

import { createRouter, createWebHistory } from 'vue-router'
import MedicalPlanDocView from '../views/MedicalPlanDocView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'medicalPlanDocView',
      component: MedicalPlanDocView
    },
    {
      path: '/callback',
      name: 'callback',
      redirect: to => {
        const code = to.query.code as string
        sessionStorage.setItem("code",code)
        return "/"
      }
    }
  ]
})

export default router

初始Nginx配置

server {
    server_name  front;
    listen       80;
    listen  [::]:80;

    root   /usr/share/nginx/html;
    index  index.html index.htm;

    location / {
        try_files $uri $uri/ /index.html;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

尝试修改后的Nginx配置(未生效)

server {
    server_name  front;
    listen       80;
    listen  [::]:80;

    root   /usr/share/nginx/html;
    index  index.html index.htm;
    location / {
        try_files $uri $uri/ /index.html;
    }
    location /callback {
        try_files $uri $uri/ /;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

原因分析与修复方法

问题原因

  1. 初始Nginx配置的location /规则已经正确:try_files $uri $uri/ /index.html会把所有找不到对应静态文件的请求转发到index.html,让Vue Router处理路由逻辑,包括/callback路径。
  2. 修改后的配置新增了location /callback块,其中try_files $uri $uri/ /;的最后一个参数是/,Nginx会直接把请求重定向到根路径,丢失了原请求的code查询参数,且这个块的优先级高于location /,导致Vue Router完全没机会处理/callback的路由逻辑。

修复方法

直接恢复到初始Nginx配置即可,不需要新增location /callback块。如果恢复后仍有问题,按以下步骤排查:

  • 执行nginx -s reload确保Nginx加载了最新配置
  • 确认Vue项目的import.meta.env.BASE_URL为/(若部署在根路径),打包后文件正确放置在/usr/share/nginx/html目录下
  • 清除浏览器缓存后重新测试

如果想明确指定/callback的处理规则,也可以保留初始配置,或者将location /callback修改为和根路径一致的规则,但这属于冗余配置:

location /callback {
    try_files $uri $uri/ /index.html;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 16:22:39