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

Vue3项目直接通过URL访问路由出现Not Found错误求助

Vue3 history模式下Apache直接输入路由404的解决方法

你遇到的问题是因为Vue Router使用了createWebHistory()(history模式):通过router-link跳转时是前端内部路由切换,不会触发服务器请求;但直接在地址栏输入URL时,Apache会尝试寻找对应物理文件,而这些路由是前端虚拟路由,服务器没有对应资源,因此返回404。

以下是具体解决步骤:

1. 添加URL重写规则

在项目部署目录下创建.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>
  • 如果项目部署在子目录(比如/my-vue-app/),需要修改RewriteBase和最后一行的路径:
    RewriteBase /my-vue-app/
    RewriteRule . /my-vue-app/index.html [L]
    

2. 开启Apache的mod_rewrite模块

  • 打开Apache的主配置文件(通常是httpd.conf或apache2.conf)
  • 找到#LoadModule rewrite_module modules/mod_rewrite.so,删除前面的#启用模块
  • 重启Apache服务

3. 子目录部署额外配置

如果项目部署在Apache的子目录,还需要在项目配置文件中设置公共路径:

  • 若使用Vue CLI,在vue.config.js中添加:
    module.exports = {
      publicPath: '/my-vue-app/'
    }
    
  • 若使用Vite,在vite.config.js中添加:
    import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    
    export default defineConfig({
      plugins: [vue()],
      base: '/my-vue-app/'
    })
    

内容的提问来源于stack exchange,提问作者Павел Саенко

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 15:36:21