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

Vue-Router在Node.js生产环境中URL路径返回404问题求助

Vue3生产环境History模式路由访问问题解决

1. 检查服务器重定向配置(核心问题)

你之前的重定向可能是直接跳转到首页,而非让index.html接管所有路由请求。不同服务器的正确配置如下:

Nginx

修改配置文件,确保所有请求转发到index.html:

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

避免使用rewrite ^/(.*)$ /index.html permanent;这类强制跳转,会丢失路由参数。

Apache

在dist文件夹根目录创建.htaccess文件:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

IIS

在web.config中添加重写规则:

<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Handle History Mode" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/index.html" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

2. 确认Vue Router配置正确性

确保路由使用createWebHistory模式,且BASE_URL与部署路径匹配:

// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Customers from '../views/Customers.vue'

const routes = [
  {
    path: '/customers',
    name: 'Customers',
    component: Customers
  },
  // 其他路由配置
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

export default router

3. 配置部署基础路径(BASE_URL)

如果部署在网站根目录,确保构建工具的基础路径设置为/:

Vite项目(vite.config.js)

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  base: '/' // 子路径部署改为对应路径,如'/my-app/'
})

Vue CLI项目(vue.config.js)

module.exports = {
  publicPath: '/' // 同上
}

4. 排查路由守卫或全局拦截

检查是否有全局路由守卫(如router.beforeEach)错误地将所有请求重定向到首页,比如:

// 错误示例:会导致所有路由跳首页
router.beforeEach((to, from, next) => {
  next('/')
})

确保守卫逻辑仅在必要时跳转,比如未登录场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:55:20