快轉到主要內容

調整Hugo的permalinks,讓不同目錄下的頁面產生同一個網址

資訊科技 Hugo網站架設 Hugo
🗓️ 民國112年 癸卯年
✍ 切換正體/簡體字
目錄

Generating same URL for pages from different sections under content directory of Hugo website.

1. Hugo內容與網址管理問題
#

長久以來我都是把所有文章放在同一個/posts目錄下

content
├── posts/
│   ├── article1/
├─── ├─index.md
│   ├── article2/
├─── ├─index.md
│   ├── article3/
├─── ├─index.md
│   ├── article4/
├─── ├─index.md

這樣所有文章都會產生/posts/為前綴的網址,等同是永久連結:

https://example.com/posts/article1/
https://example.com/posts/article2/

問題來了,久而久之,文章越來越多,現在已經超過500個資料夾了,難以管理呀。我想要把文章依照類別放目錄,例如這樣:

content
├── posts/
│   ├── article1/
├─── ├─index.md
├── linux/
│   ├── article2/
├─── ├─index.md
├── mobilephone/
│   ├── article3/
├─── ├─index.md
├── technology/
│   ├── article4/
├─── ├─index.md

但是,如果直接這樣放,生成的文章網址就會變成下面這樣,每個網址由Hugo自動帶入section,造成困擾。

https://example.com/posts/article1/
https://example.com/linux/article2/
https://example.com/mobilephone/article3/
https://example.com/technology/article4/

為什麼?因為我常常用categories的front matter來調整文章分類,文章的網址最好是固定的日後才能方便移動:

https://example.com/posts/article1/
https://example.com/posts/article2/
https://example.com/posts/article3/
https://example.com/posts/article4/

要解決這個問題,得調整Hugo生成網址的設定。我想要讓不同目錄section下的文章最終都擁有一樣的/posts/網址,即永久連結。

2. 解決方案
#

讓我們再看一次Hugo的渲染機制。

Hugo網頁結構是使用名為section的機制來控制的,content下的每個目錄都是一個section。

如果Hugo網站根目錄的content有以下多個目錄section,每個目錄分別有一篇文章article

content
├── section1/
│   ├── article1/
├─── ├─index.md
├── section2/
│   ├── article2/
├─── ├─index.md

那麼最終生成的文章網址如下:

https://example.com/section1/article1 #對應content/article1/index.md
https://example.com/section2/article2 #對應content/article2/index.md

接著看你的主題怎麼實作,像我使用的 Blowfish主題的首頁「全部文章列表」只能讀單個section下的文章,變成單一列表。因此secion1的列表就不會包含section2的內容。

由此可知,Hugo的section會區隔開文章。

要讓不同section下的文章產生同一個網址,就得到Hugo網站根目錄的設定(config.toml或config.yaml)設定「Permalinks」的產生規則。

根據Hugo官方文件 URL management,只要在檔案新增[permalinks]區塊,加入以下內容就可以了

 [permalinks]
   [permalinks.page]
     posts = '/posts/:filename/'
     linux = '/posts/:filename/'
	 mobilephone = '/posts/:filename/'
	 technology = '/posts/:filename/'
   [permalinks.section]
     posts = '/posts/'
     linux = '/posts/'
	 mobilephone = '/posts/'
	 technology = '/posts/'

posts = '/posts/:filename/'指定,讓/posts目錄下的文章產生/posts的網址;同理,linux = '/posts/:filename/'/linux目錄下的文章也產生/posts的網址。

:filename是token,代表以文章markdown的檔名或page bundle目錄名稱來命名網址。

如此一來,位於不同目錄的頁面就會有相同的網址了。至於沒有定義在[permalinks]的目錄,Hugo就會照舊生成帶有section的網址。

相關文章

為什麼我要用Disqus取代Giscus當作Hugo留言板
資訊科技 Hugo網站架設 Hugo Github
Hugo框架畫廊主題的實踐 ~ 艦娘乳図鑑
資訊科技 Hugo網站架設 Kantai Collection Hugo
自訂Hugo的RSS訂閱,過濾特定文章不讓其出現在RSS列表
資訊科技 Hugo網站架設 Hugo RSS Feed

留言板

此處提供二種留言板。點選按鈕,選擇您覺得方便的留言板。要討論程式碼請用Giscus,匿名討論請用Disqus。

這是Giscus留言板,需要Github帳號才能留言。支援markdown語法,若要上傳圖片請貼Imgur連結。您的留言會在Github Discussions向所有人公開。

這是Disqus留言板,您可能會看到Disqus強制投放的廣告。有時留言可能會被系統判定需審核,導致延遲顯示,請見諒。