vue-router history模式下 nginx配置

背景

首先我们的前端是分成了 pc端 和 移动端 两部分,并非一个整体项目,但是目前网站域名只有一个,即 www.xxx.com
其次 pc端 项目是多页面项目,而移动端项目是基于 vue 的 SPA,所以 pc端 和 移动端的访问路径是不一样的
最后移动端的路由由 hash模式 更改为 history模式,此模式需要后端 nginx 支持

需求

当用户对网站进行访问的时候,动态读取客户端是pc 还是移动端,从而设定不同的根站点
当访问的页面不存在,需要进行重定向到首页

前端路由

let r = {
	mode: 'history',
  	routes: [
      {
          path: '/a',
          component: a
      },
      {
          path: '/b',
          component: b,
      },
      {
          path: '/c',
          component: c,
      },
      {
          path: '/d',
          component: d,
      },
      {
          path: '/f',
          component: f,
      },
      {
          path: '/e',
          component: e,
      },
      {
          path: '/l',
          component: l,
      },
      {
          path: '/h',
          component: h,
      },
      {
          path: '*',  // 重定向,防止错误路径
          redirect: '/a'
      }
    ]
}

nginx配置

########### 每个指令必须有分号结束。#################

http {
    server {
        keepalive_requests 120; #单连接请求上限次数。
        listen       80;   #监听端口
        server_name  www.xxx.com;   #监听地址       
        set $mobile_rewrite do_not_perform;  //默认当前客户端是 pc端
        if ($http_user_agent ~* "(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge                    |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os )?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows         ce|xda|xiino") {
               set $mobile_rewrite perform;  //判断当前客户端是移动端
              
        }   
             
        location / {
             root   /var/www/html/m;  //移动端访问的根站点
             if ($mobile_rewrite = do_not_perform) {
                 root /var/www/html/dig;  //pc端访问的根站点
             }
             index  index.html index.htm;  // 默认页面
             try_files $uri $uri/ /index.html;   //后端支持 hash 变为 history 的关键代码
        }
    }
    error_page 404  http://www.xxx.com; #当路径错误的时候返回首页
}

总结

代码的实现非常简单,需要注意的就是两点:
  • 后端的404 重定向用于 pc端,前端的重定向还是在 router 里
  • ’ try_files $uri $uri/ /index.html’ 是支持 vue-router mode 为 history 的关键部分,不可省略
  • 如果pc 和移动端属于不同域名,那么 nginx 中的判断部分可以省略了
  • 欢迎交流和留言

猜你喜欢

转载自blog.csdn.net/zhai_865327/article/details/90201906