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

Vue.js 2中移除Vue Router URL的#符号问题求助

解决VueRouter History模式下的路由失效与资源加载问题

核心问题根源

开启history模式后,浏览器刷新会直接向服务器请求domain/main.html/路径,但服务器默认无对应资源,因此返回404;资源加载失败则多是因为使用相对路径,路由切换后资源基准路径发生变化。

分步解决方案

1. 配置服务器回退规则

根据你使用的服务器类型,设置所有请求都指向main.html:

  • Nginx:在配置文件的location块中添加
    location / {
      try_files $uri $uri/ /main.html;
    }
    
  • Apache:在项目根目录创建.htaccess文件,写入
    <IfModule mod_rewrite.c>
      RewriteEngine On
      RewriteBase /
      RewriteRule ^index\.html$ - [L]
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule . /main.html [L]
    </IfModule>
    
  • Vue CLI开发服务器:在vue.config.js中配置
    module.exports = {
      devServer: {
        historyApiFallback: {
          index: '/main.html'
        }
      }
    }
    

2. 修复资源加载路径

  • 将项目中图片、脚本、样式等资源的路径改为绝对路径,或在vue.config.js中配置publicPath:
    module.exports = {
      publicPath: './' // 也可设置为项目根路径,如 '/your-project/'
    }
    
  • 确保路由base配置匹配部署路径:
    const router = new VueRouter({
      mode: 'history',
      base: '/main.html/',
      routes
    })
    

3. 调整通配路由规则

将通配路由改为直接渲染首页组件,避免刷新时的路径冲突:

{ path: '*', component: Home } // Home为你的首页组件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:20:31