我的博客

更换域名

目录
  1. 重定向
    1. url 映射代码
    2. 测试
    3. 申请新 https 证书
  2. 博客部署到 blog 目录下
  3. 修改百度统计代码
  4. 域名解析
  5. Valine 评论和阅读统计

这次更换域名改动不少,让我想换域名的直接原因是实习的公司内网屏蔽了所有 .top 域名,而我的博客在百度的收录一直有问题,也怀疑是域名的问题。除了把域名从 codeplot.top 换到 es2q.com 外我还做了如下调整:

  1. 改写所有文章页面 url ,使只包含字母,数字、连字符和下划线
  2. 博客整体移入 blog 文件夹
  3. 部署时也部署到 GitHub Page 的 blog 目录下

因为我在 leetcode 和 SegmentFault 等网站还留了一些我博客的链接,而且在谷歌上还有几百的索引页面,所以需要做原域名的重定向,但是由于更改了很多页面的 url,所以需要做 url 的映射表。然后评论系统和阅读量统计也都需要修复。

重定向

我在新买的华为云服务器上部署了重定向程序,首先通过 sitemap 得到所有文章的 url, 然后手动改写 url,去除了中文和特殊符号等,要同步修改 hexo 的 source 下的 md 文件名。重定向的程序是用 Flask 写的,注意要指明状态码 301(Flask 的 redirect 默认是 302)即永久转移。

用到的 url.txt 文件每行内容是新 path\t原path

url 映射代码

不仅做了映射,还记录请求信息,帮助分析哪里还有未更新的链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from flask import Flask, request, redirect
from urllib import parse
import json, time
app = Flask(__name__)

ud = {'index.html': '/blog/index.html', '/': '/blog/'}
f = open('url.txt', encoding='gbk')
for l in f:
nu, ou = l.split('\t')
ud[ou.strip()] = nu
host = 'http://127.0.0.1:4000' # 用于本地测试的域名
host = 'https://es2q.com' # 新域名
f.close()

@app.before_request
def be1():
to_url = host + '/blog' + request.path
Host = request.headers.get('Host')
ua = request.headers.get('User-Agent')
ac = request.headers.get('Accept')
ace = request.headers.get('Accept-Encoding')
acl = request.headers.get('Accept-Language')
try:
ip = request.headers['X-Forwarded-For'].split(',')[0]
except:
ip = request.remote_addr
try:
if request.path in ud:
to_url = host + ud[request.path]
elif parse.quote(request.path) in ud:
to_url = host + ud[parse.quote(request.path)]
elif (request.path+'/') in ud:
to_url = host + ud[request.path+'/']
except Exception as e:
with open('redirect.log', 'a') as f:
f.write(request.path + '\t' + 'err' + '\t' + str(e) + '\n')
with open('redirect.log', 'a') as f:
f.write('%d\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' %(int(time.time()), ip, Host, ua, ac, ace, acl, request.path, to_url, request.referrer))
return redirect(to_url, code=301)


if __name__ == '__main__':
app.run(port=8001)

测试

测试是否所有链接可以正常访问的脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import requests
from bs4 import BeautifulSoup
from tqdm import tqdm

ud = {}
f = open('url.txt')
for l in f:
nu, ou = l.split('\t')
ud[ou.strip()] = nu
host = 'http://127.0.0.1:8001'
l = []
for k in ud:
r = requests.get(host + k)
if r.status_code != 200:
print('error', k)
continue
b = BeautifulSoup(r.content.decode(), features='html.parser')
l.append([b.title, k])
#for ll in l:
# print(ll)

还写了一个检查 md 文件中是否有敏感词的脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
dicts = ['xxx.txt']
wds = []
for d in dicts:
with open(d, encoding='utf8') as f:
for l in f:
wds.append(l.strip())
import os
from tqdm import tqdm
tdir = 'source\\_posts\\'
fs = os.listdir(tdir)
err = []
for fi in tqdm(fs):
with open(os.path.join(tdir, fi), encoding='utf8') as f:
txt = f.read()
for wd in wds:
if wd in txt:
print(fi, wd)
err.append((fi, wd))
for e in err:
print(e)

之前有一次我的百度索引量突然减到 1,我怀疑可能是一篇思政课笔记中有敏感词汇。

申请新 https 证书

原来是 GitHub Pages 给的证书,现在需要一个新的,这个网站:https://freessl.cn/ 非常好用。

博客部署到 blog 目录下

考虑以后整个网站可能有除了博客以外的内容,所以考虑把整个博客放到 https://es2q.com/blog/ 下。可以通过修改 _config.yml:

1
2
3
4
5
6
7
# URL
url: https://es2q.com/blog/
root: /blog/

# Directory
source_dir: source
public_dir: public/blog/

但是这样对 hexo-deployer-git 并不有效。

因为它的代码中直接复制了 public_dir 的内容,然后 push 到 github 上。

我是通过修改 hexo-deployer-git 的代码实现了 push 到 blog 目录下,需要修改的文件是:\node_modules\hexo-deployer-git\lib\deployer.js

首先修改代码开始的 publicDir,直接写成 ‘public’。

1
var publicDir = 'public';//this.public_dir;

第二找到这一句 return fs.copyDir(publicDir, deployDir, opts);

在下面添加:

1
2
3
4
5
6
7
8
9
10
11
  // 前面的内容这里省略了
return fs.copyDir(publicDir, deployDir, opts);
}).then(function() {
return fs.copyFile(publicDir+'/blog/CNAME', deployDir+'/CNAME'); // 复制 CNAME,Github Pages 绑定域名用的
}).then(function() {
return fs.copyFile(publicDir+'/blog/index.html', deployDir+'/index.html'); // 把 index 复制到根目录来一份
}).then(function() {
return fs.copyFile(publicDir+'/blog/sitemap.xml', deployDir+'/sitemap.xml'); // 把 sitemap 复制到根目录一份,如果没有生成 sitemap就不需要这个
}).then(function() {
return fs.copyFile(publicDir+'/blog/baidusitemap.xml', deployDir+'/baidusitemap.xml'); // baidu sitemap,同上一条
}) // 后面还有内容,是原来的代码

修改百度统计代码

更换了域名所以要重新生成百度统计代码。可以放到主题文件的 header 或者 footer 里。

域名解析

把新域名解析到 GitHub Pages,同时调整 GitHub 仓库配置,然后把旧域名解析到运行重定向服务的服务器上,并配置好 Nginx。

Valine 评论和阅读统计

阅读统计 id 前面要添加 /blog/。评论则需要修改后台数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%- partial('_partial/article', {post: page, index: false}) %>
<script src='//unpkg.com/valine/dist/Valine.min.js'></script>
<!-- id 将作为查询条件 -->
<span id="/blog/<%= page.path %>" class="leancloud_visitors" data-flag-title="<%= page.title %>">
<em class="post-meta-item-text">阅读量 </em>
<i class="leancloud-visitors-count"></i>
</span>
<p>评论无需登录,可以匿名,欢迎评论!</p>
<div id="vcomments"></div>
<script>
new Valine({
el: '#vcomments',
appId: 'vdTqlvkiIk2AmomVRXrR9kb0-gzGzoHsz',
appKey: 'yrlSqvbHUJqqVzH2rb0t2X9B',
visitor: true
})
</script>

评论无需登录,可以匿名,欢迎评论!