加载中

单页应用history模式nginx配置

前言

hash 模式时将路径转换为 /#/xxx/xxx 模式,页面不刷新,请求资源路径不变,从而实现内容的跳转。

history 模式直接去掉了 /#/,如果服务器不配置的话,直接就是 404。

服务器实现 history 模式的原理:
只要请求某个应用下的资源,都返回这个应用的入口回去(index.html),路径什么的都交给入口处理。

实现

nginx 有很多方法都能实现这个功能,这里介绍通过 error_page 实现的方法

以 vue 为例:

通过 error_page

  1. vue 路由基础路径设置
// xxx.com 直接访问应用时无需修改 base
const router = new VueRouter({
  base: process.env.BASE_URL,
  mode: 'history'
  /* ... */
})
// xxx.com/xxx 访问应用时需修改 base
const router = new VueRouter({
  base: '/demo',
  mode: 'history'
  /* ... */
})
  1. vue 根路径配置

history 模式下不能使用相对路径 ./,因为 history 模式下路径不是以 /#/ 表示,使用相对路径会使路径出错导致某些资源 404

// xxx.com 直接访问应用时设为 /
module.exports = {
  publicPath: '/',
  /* ... */
}
// xxx.com/xxx 直接访问应用时设为 xxx/
module.exports = {
  publicPath: 'demo/',
  /* ... */
}
  1. nginx 配置
# 根据实际情况设置一下 root
# 可以写 location 外面(全局),也可以写 location 里面(局部)
root  /www/server/nginx/html;
# xxx.com 访问应用
location / {
   index index.html;
   error_page 404 /index.html;
}
# xxx.com/xxx 访问应用
location /demo {
   index index.html;
   error_page 404 /demo/index.html;
}

利用 error_page 的特性,只要是 404 页面都返回相应的入口文件回去。

通过 try_files

还可以使用 try_files 实现

# xxx.com 访问应用
location / {
    try_files $uri $uri/ /index.html;
}

还可以使用 rewrite 实现 … nginx NB

posted @ 2020-02-24 21:02  jialeYang  阅读(314)  评论(0编辑  收藏  举报