Vue-router的history模式配置(apache)

1,488 阅读2分钟

缘由

使用vue-router如果使用默认的hash模式,会使得URL上出现一个#字符来拼接地址。但是如何配置好一个history模式,官方文档没有给出具体的说明。 (可能是它觉得这个太简单了?)

官方给出的说明:

vue-router 默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。如果不想要很丑的 hash,我们可以用路由的 history 模式,这种模式充分利用 history.pushState API 来完成 URL 跳转而无须重新加载页面。

实际效果:URL去掉#。

此篇文章将单独展开官网后端配置例子关于Apache的详细配置步骤。

运行环境

  1. 已配置LAMP环境的CentOS8
  2. vue-router v3.x版本
  3. vue 2.0

(现在看上去这版本好老,哈哈)

步骤

1. 配置vue-router

在router-index.js中配置vue-router,修改mode属性为history,此处的base属性是我们部署在服务器上基于根目录的子目录位置。

const router = new Router({
  mode: 'history',
  base:'/community', // 线上访问地址: xxx.cn/community/...
  routes: [...],
})

2. 编辑Apache mod_rewrite配置

在我们部署的子目录上,创建.htaccess文件(分布式配置文件)。

image.png

编辑如下内容,其中ReweiteBase需要填写我们的子目录位置:

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

如果在根目录,上述应该修改为:

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

注意!此处的RewriteRule中的点和/index中间是有空格的,如果如果这里配置错误,在history模式下用户重新刷新页面是找不到对应路由的,此时会返回404 no found.(代表404分,找不到对手了)

image.png

3. 设置Apache httpd conf配置

当然,单纯地创个文件怎么可能会生效呢?我们还需要配置让这个文件生效的地方。

找到apache的httpd.conf配置文件,位于/etc/httpd/conf/httpd.conf

将对应的AllowOverride修改为All。

image.png

4. 重新启动httpd

systemctl restart httpd

最后重新打包部署上去,就会发现我们的网站上的URL不会出现#字符并且可以正常访问各个路由啦。

graph TD
xxx.cn/community/#/component --> xxx.cn/commnunity/component

参考文档: