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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章