这也是从WordPress迁移到Gridea&github pages的后遗症之一.
我在WP那边的url格式是https://www.sunjianbo.com/xxx.html,而弄好Gridea之后发现url格式是https://www.sunjianbo.com/post/xxx/.因为是老站嘛,搜索引擎还是有一些关键词可以搜到的,所以昨天发现了问题,从搜索引擎那边链接打开的页面都会404.
我第一个想法就是通过.htaccess做url的rewrite,但是搜索一下发现github pages并不支持这种方式.
好在还知道<meta http-equiv="refresh" content="2; url='/'">
标签可以做页面的定时跳转和刷新,再结合使用<link rel="canonical" href="" />
标签来告诉搜索引擎新的规范链接地址.
思路说完了,那么以下是详细步骤:
1.修改Gridea主题设置
开启,精简url模式这是为了去掉url中的/post/,不用gridea的可以无视.
2.批量创建html文件
我这里通过Python代码遍历post目录下所有文章,提取文件名,替换后缀名,在指定目录生成.html文件.
代码如下:
#conding=utf8
import os
g = os.walk("D:\IDE\Gridea\Documents\Gridea\posts")
out = "D:\IDE\Gridea\Documents\Gridea\output\"
for path,dir_list,file_list in g:
print(len(file_list))
for file_name in file_list:
# print(os.path.join(path, file_name) )
print(os.path.splitext(file_name)[0])
outName = os.path.splitext(file_name)[0] + ".html"
with open(out + outName, 'w') as f: # open()函数可以判断文件是否存在,如果不存在,则创建文件
myurl = "www.sunjianbo.com/" +os.path.splitext(file_name)[0]
message = """<html>
<head>
<meta http-equiv="refresh" content="0; url=https://myurl/">
<link rel="canonical" href="https://myurl/" />
</head>
<body>
</body>
</html>"""
message = message.replace("myurl",myurl)
f.write(message)
3.上传到github
打开.html查看是否没有问题,删除多余的没用文件,比如我这里还生成了一个.DS_Store.html
*´∀`)
然后手动上传到github,不能通过Gridea上传因为他会清空output目录自己再生成一遍文章,我们的html文件会在同步前被删除.
到output目录打开终端
git add .
git commit -m "for rewrite"
git pustt
当然网页上传也可以,不过上传文件限制一次100,文章多的话更麻烦一点.