Using Vue Router History Mode

Vue:2.6.11

Vue-Router:3.2.0

在 Vue Router 中有 history 跟 hash 兩種模式。

在 hash 模式下,URL 的顯示會類似 https://localhost#home,而 history 則是與一般 Restful URL 的形式相同,像是 https://localhost/home 。

通常使用都會以 history 模式為主,除了美觀以外,也較不會跟 URL 的 anchor 功能衝突。

在初學用 Vue 架設 SPA 網站時,有不少人會遇到在 history 模式下,將編譯好的 code 放到 HTTP Server 上卻無法執行。

其實這個問題很容易,只要理解運作原理,基本上問題就可以自動解決了。

SPA and MPA

首先,要先理解 Single Page Application (SPA) 和 Multi Page Application (MPA) 的運作原理。

MPA 較好理解,就是根據 URL 路徑,由 HTTP Server 去載入個別的檔案。

MPA

graph LR
    /home-->HTTPServer["Http Server"]
    /about-->HTTPServer["Http Server"]
    /info-->HTTPServer["Http Server"]
    HTTPServer["Http Server"]-->home.html
    HTTPServer["Http Server"]-->about.html
    HTTPServer["Http Server"]-->info.html

而 SPA 則是會載入同一支檔案,檔案再根據 URL 路徑去選擇要載入的檔案。

SPA

graph LR
    /home-->HTTPServer["Http Server"]
    /about-->HTTPServer["Http Server"]
    /info-->HTTPServer["Http Server"]
    HTTPServer["Http Server"]-->index.html["index.html(v-router)"]
    index.html["index.html(v-router)"]-->home
    index.html["index.html(v-router)"]-->about
    index.html["index.html(v-router)"]-->info

Server Configuration

因此在 history 模式下,HTTP Server 要做的設定就是 將進入的路徑都指到 index.html,再由 index.html 裡面的 Vue Router 去控制。

如果沒有設定的話,HTTP Server 就會去找路徑相對應的檔案,那就會出現 404 not found 的狀況惹。

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;
}
Categories: Vue