Hugo 多语言站点中 404 页面的重定向规则

本页内容

在 Hugo 多语言站点中,一般需要为 404 页面设置额外的重定向规则。

问题

在多语言站点中,有几个情况,假设 en 为默认语言。

语言defaultContentLanguageInSubdir404 页面
enfalse/404.html
entrue/en/404.html
zh-hanstrue/zh-hans/404.html
zh-hanttrue/zh-hant/404.html

可以看到 404 页面也是多语言化的,我的目标方案是根据首个路径匹配语言,尝试查找 404 页面,匹配失败则使用默认语言的 404 页面。

Nginx

 1server {
 2    location ~* ^/([^/]+) {
 3        index  index.html index.htm;
 4        error_page 404 = @error;
 5    }
 6
 7    error_page 404 /404.html;
 8    location @error {
 9        try_files /$1/404.html /404.html =404;
10    }
11}
  1. 这里先定义了一个 @error 块,利用 try_files 于第一个路径下尝试匹配 404.html ,失败则使用默认的 404 页面。
  2. 如果你开启了 defaultContentLanguageInSubdir,在站点构建时,还需要将默认的 404 页面复制到根目录。

也许还可以根据请求头,以获取用户偏好的语言进行更准确的语言匹配,由于笔者经验有限,只能后续有空再研究研究。

Netlify

 1[[redirects]]
 2  from = "/:lang/*"
 3  to = "/:lang/404.html"
 4  status = 404
 5
 6[[redirects]]
 7  from = "/*"
 8  to = "/en/404.html" # Replace the "en" to your default language code.
 9  # to = "/404.html" # Use it when a monolingual site or "defaultContentLanguageInSubdir" is disabled.
10  status = 404

Cloudflare Pages

Cloudflare Pages 已经为你设置好 404 页面重定向规则,你无须做额外配置。

razonyang
2024年7月23日星期二 2022年7月31日星期日