Nginx 部署 vue项目 (history模式)

大家都知道,vue router有两种模式:

1,hash模式

hash模式应该是平时大家用的最多的一种模式,它的标志是路由地址都会加上#。

2,history模式

history模式则不会加上#号,这样url看起来比较干净。但是使用history模式,会导致一个问题,就是在某个路由页面上刷新的时候或者直接访问多级路由url的时候会报404.

import Vue from 'vue';
import Router from 'vue-router';

Vue.use(Router);

const router = new Router({
  mode: 'history', // 访问路径不带井号  需要使用 history模式;如果不想配置后端,那就是默认                                            
                   // hash模式
  base: '/home',  // 基础路径
  routes: [
    {
      path: '/index',
      name: 'index',
      component: resolve => require(['@/views/index'], resolve) // 使用懒加载
    }
  ]
});

所以,为了解决这个问题,需要在后端做一点处理。

如果是Apache做代理服务:

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

如果是nginx做代理服务:

location / {
  try_files $uri $uri/ /index.html;
}

Nginx知识补充:

try_files 指令:

语法:try_files file ... uri 或 try_files file ... = code

其作用是按顺序检查本地(服务器)文件是否存在,返回第一个找到的文件或文件夹(结尾加斜线表示为文件夹),如果所有的文件或文件夹都找不到,会进行一个内部重定向到最后一个参数。

需要注意的是,只有最后一个参数可以引起一个内部重定向,之前的参数只设置内部URI的指向。最后一个参数是回退URI且必须存在,否则会出现内部500错误。命名的location也可以使用在最后一个参数中。与rewrite指令不同,如果回退URI不是命名的location那么args不会自动保留,如果你想保留args,则必须明确声明。

原生 Node.js:

const http = require('http')
const fs = require('fs')
const httpPort = 80

http.createServer((req, res) => {
  fs.readFile('index.htm', 'utf-8', (err, content) => {
    if (err) {
      console.log('We cannot open "index.htm" file.')
    }

    res.writeHead(200, {
      'Content-Type': 'text/html; charset=utf-8'
    })

    res.end(content)
  })
}).listen(httpPort, () => {
  console.log('Server listening on: http://localhost:%s', httpPort)
})

 

 

参考:

https://www.cnblogs.com/mmzuo-798/p/10871750.html

https://router.vuejs.org/zh/guide/essentials/history-mode.html

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值