Ghost 重定向到新域名+子路径

网页

Ghost 要求 使用 redirects.json 来处理重定向。接着,把做好的 JSON 文件上传到 Ghost 后台/Settings/Labs/Beta Features 里。在这里,你也可以下载当前正在使用的 redirects.json

上传 redirects.json 到 Ghost 后台/Settings/Labs/Beta Features

这里给出一个简单的例子。from 后面指明了重定向的来源,to 后面代表重定向的目标。permanent 则有两个值,true 代表 301 重定向,false 代表 302 重定向。

[
  {
    "from": "old_path",
    "to": "new_path",
    "permanent": true
  }
]

我希望的效果是把旧文章重定向到 新域名/blog/ 。如果我原有的 URL 是 https://old.domain/post_name ,我希望把它重定向到 https://new.domain/blog/post_name

[
  {
    "from": "post_name",
    "to": "https://new.domain/blog/post_name",
    "permanent": true
  }
]

每一篇我都要做如上的重定向。可是,我的博客有很多篇内容,不可能手动填写,效率过低。所以,需要找一个方法自动生成。

我写了一个 python 程式生成 redirect.json

这个程序使用 Ghost 提供的 Content API 来抓取每一篇文章的 slug 。在使用程序之前,你需要先在 Settings/Integrations/Custom Integrations 里,创建一个新的 API。之后,准备好 Content API Key,待会儿我们会用到。

image-20220401181606768

如果你希望重定向的来源、目标、重定向类型(301/302)与我稍有不同,应自行修改第 15 行到第 18 行的代码

由于 Ghost 禁止爬虫,因此我在程序中添加了 Firefox 的 User*-*Agent request header headers={'User-Agent': 'Mozilla/5.0'} ,从而欺骗 Ghost 误以为我们是 Firefox 用户。

from urllib.request import Request, urlopen
import json

website = 'https://your_old_ghost_domain.com' # input your website with https/http but without trailing slash
content_api_key = 'YOUR_API_Key_Here' # input your content_api_key

url = website + '/ghost/api/v3/content/posts/?key=' + content_api_key + '&limit=all&include=tags'
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
web_byte = urlopen(req).read()
data = json.loads(web_byte.decode())

redirections = []
for post in data['posts']:
    redir = dict()
    redir['from'] = post['slug']
    redir['to'] = 'https://your_new_domain.com/blog/' + post['slug']
    redir['permanent'] = True
    redirections.append(redir)
    
print(json.dumps(redirections, indent = 4))

另外,你需要修改第四五行。

  • 以你自己的 Ghost 网站 URL(比如上图里的 API URL 行)代替 website 原本的变量内容

    • 需要包含 https/http 协议在 URL 中
    • 末尾斜杠需要移除
  • 把你刚才准备好的 Content API key 代替 content_api_key 原本的变量内容。

改完后,应该类似这样:

website = 'https://my_old_domain.com' # input your website with https/http but without trailing slash
content_api_key = '32890djsfkljlk2890djlkj2l' # input your content_api_key

运行 Python 程序(按需更改路径):

python3 generate_json.py

得到输出结果如下:

[
    {
        "from": "post_name_abc",
        "to": "https://your_new_domain.com/blog/post_name_abc",
        "permanent": true
    },
    {
        "from": "post_name_xyz",
        "to": "https://your_new_domain.com/blog/post_name_xyz",
        "permanent": true
    },
    {
        "from": "post_name_efg",
        "to": "https://your_new_domain.com/blog/post_name_efg",
        "permanent": true
    }
]

创建一个新的 .json 格式的文件,把刚才输出的结果复制进去。接着,把文件上传到 Ghost 后台/Settings/Labs/Beta Features 里。完成。