码迷,mamicode.com
首页 > Web开发 > 详细

Vue路由重写# 与 Web服务器路由重写双配置实现路由重写

时间:2020-03-31 22:35:33      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:tac   const   mda   用户   加载   das   apach   自动跳转   dash   

前言
vue路由组件我使用的vue-router
web服务器使用nginx

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

const router =new Router({
mode: ‘history‘,
routes: [...]
})
1
2
3
4
不过这种模式需要后台配置支持。如果后台没有正确的配置,当用户在浏览器直接访问就会返回 404

Web服务器配置
如果要使用history模式,则需要进行服务器配置
所以,要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是app 依赖的页面
下面分别介绍Nginx和Apache下的重写配置

Nginx配置
location / {
try_files $uri $uri/ /index.html;
}
1
2
3
Apache配置
首先,去掉rewrite_module前面的#号注释
LoadModule rewrite_module modules/mod_rewrite.so
然后,将文档所有的AllowOverride设置为all
AllowOverride all
最后,需要保存一个.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>
1
2
3
4
5
6
7
8
小结
这么做以后,服务器就不再返回404错误页面,因为对于所有路径都会返回 index.html 文件。为了避免这种情况,应该在Vue应用里面覆盖所有的路由情况,访问错误路由即跳转指定路由,这里一般是自动跳转首页或者跳转404错误页
const router = new VueRouter({
mode: ‘history’,
routes: [
{ path: ‘*’, redirect: ‘/’,}
]
})


Vue路由重写# 与 Web服务器路由重写双配置实现路由重写

标签:tac   const   mda   用户   加载   das   apach   自动跳转   dash   

原文地址:https://www.cnblogs.com/dgmoba/p/12609123.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!