Contents

Hexo設定blog子資料夾網址

當 Hexo 部落格部署在子路徑(例如 GitHub Pages 的 Project Page)時,需要特別設定 _config.yml 的 URL 相關設定,否則靜態資源(CSS、JS、圖片)的路徑會出錯,導致樣式跑版或腳本無法載入。

為何需要設定子資料夾路徑

GitHub Pages 提供兩種部署方式:

  • User/Organization Page:網址為 https://username.github.io,部署在根目錄,不需要特別設定。
  • Project Page:網址為 https://username.github.io/project-name,部署在子路徑 /project-name/ 下,必須設定子路徑,否則所有靜態資源的路徑都會指向根目錄而失效。

_config.yml 設定說明

1
2
3
4
5
6
# URL
## If your site is put in a subdirectory, set url as 'http://yoursite.com/child' and root as '/child/'
url: https://username.github.io/blog
root: /blog/
permalink: :year/:month/:day/:title/
permalink_defaults:

各欄位說明:

欄位 說明
url 網站的完整網址,包含子路徑。用於生成絕對連結(例如 RSS、sitemap)。
root 網站根目錄的路徑,必須以 / 結尾。Hexo 會以此作為所有靜態資源的基底路徑。
permalink 文章的永久連結格式。

靜態資源路徑注意事項

設定 root: /blog/ 後,Hexo 生成的所有連結都會自動加上 /blog/ 前綴,例如:

1
2
3
4
5
6
7
8
<!-- CSS 路徑 -->
<link rel="stylesheet" href="/blog/css/style.css">

<!-- JS 路徑 -->
<script src="/blog/js/script.js"></script>

<!-- 圖片路徑 -->
<img src="/blog/images/photo.jpg">

如果使用主題的模板中有寫死絕對路徑(例如 /css/style.css),需要改為使用 Hexo 提供的 url_for() helper 函式,才能正確處理子路徑:

1
2
3
4
5
<!-- 錯誤:寫死路徑 -->
<link rel="stylesheet" href="/css/style.css">

<!-- 正確:使用 url_for -->
<link rel="stylesheet" href="<%- url_for('/css/style.css') %>">

本地測試

本地開發時可用 hexo server 預覽,Hexo 預設會在 http://localhost:4000 啟動,子路徑設定同樣會生效,網址會是 http://localhost:4000/blog/

1
hexo clean && hexo generate && hexo server

參考資料