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

Vue 3测试服务器路由刷新/地址栏跳转出现404错误求助

Vue 3部署后路由刷新/直接访问404的解决方案

问题本质

你遇到的是Vue单页应用(SPA)history模式下的服务器配置缺失问题:

  • 本地开发时,Vue的开发服务器(Vite/Cli内置)自动做了路由 fallback 处理,所有路由请求都会指向index.html,由Vue路由接管。
  • 部署到测试服务器后,服务器默认会把地址栏的路由当作真实的文件路径去查找,找不到就返回404——而这些路由其实是Vue路由定义的虚拟路径,不存在对应的物理文件。

解决步骤

1. 确认路由模式

先检查你的路由配置是否使用了history模式(如果是hash模式不会有这个问题):

import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  // 这里用了createWebHistory就是history模式
  history: createWebHistory(import.meta.env.BASE_URL), 
  routes: [/* 你的路由配置 */]
})

2. 配置服务器路由 fallback

根据你的测试服务器类型,添加对应的配置,让所有路由请求都转发到index.html:

Nginx配置

找到站点的Nginx配置文件,在location /块中添加try_files指令:

location / {
  # 优先找真实文件/目录,找不到就返回index.html
  try_files $uri $uri/ /index.html;
}

修改后重启Nginx服务。

Apache配置

在项目根目录创建.htaccess文件,写入以下内容:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  # 不重写index.html本身
  RewriteRule ^index\.html$ - [L]
  # 如果请求的不是文件/目录,重写到index.html
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

确保Apache已开启mod_rewrite模块。

IIS配置

  1. 安装IIS的URL Rewrite模块
  2. 在项目根目录创建web.config文件,写入:
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Handle Vue 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>

3. 子路径部署额外配置

如果你的项目部署在服务器的子路径下(比如http://test-server/my-app/):

  • 在Vite的vite.config.js中配置base:
    export default defineConfig({
      base: '/my-app/' // 对应部署的子路径
    })
    
  • 或在Vue CLI的vue.config.js中配置publicPath:
    module.exports = {
      publicPath: '/my-app/'
    }
    
  • 路由的createWebHistory会自动读取这个base路径,无需额外修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 06:13:26