本文最后更新于:2020年6月6日 上午

记录在hexo博客在云服务器部署时遇到的两个问题:免密git和自动备份,以及公式渲染引擎mathjax开启问题。

问题

参考Hexo博客部署到腾讯云服务器1后遇到了两个问题:

  1. 每次在本地部署博客时都要重复输入密码

    deploy:
        type: git
        repo: root@***(服务器ip,内网外网都行):/home/git/blog.git    #仓库地址
        branch: master    #分支
  2. 备份时hexo自带的backup无效

    backup:
        type: git
        repo: root@***(服务器ip,内网外网都行):/home/git/backup.git    #仓库地址
        branch: master    #分支

免密git

在这一部分参照了使用Git+Hooks实现Hexo站点自动部署到CentOS服务器上2的配置SSH免密登陆步骤。

$ ssh-copy-id -i ~/.ssh/id_rsa.pub your_user_name@HostIP  //添加公钥
$ ssh your_user_name@HostIP //验证是否添加成功

因为部署时用的root上传,因此这里的your_user_name设置gitroot两个。添加成功后ssh -v git@HostIPssh -v root@HostIP显示Welcome to XXX !

自动备份

这里我按照deploy的流程在服务器设置了自动化备份1,主要思路是在服务器设置一个独立的文件夹backup,再用类似deploy的钩子blog.git,构造一个备份的钩子deploy.git将博客的备份文件上传。

  • 获取root权限

    $ su root
  • 建立git仓库

    $ cd /home/backup
    $ git init --bare backup.git
  • 修改backup.git权限

    $ chown git:git -R backup.git
  • /home/hexo/backup.git 下,有一个自动生成的 hooks 文件夹,我们创建一个新的 git 钩子 post-receive,用于自动部署。

    $ vim backup.git/hooks/post-receive
  • i 键进入文件的编辑模式,在该文件中添加两行代码(将下边的代码粘贴进去),指定 Git 的工作树(源代码)和 Git 目录

    #!/bin/bash 
    git --work-tree=/home/backup --git-dir=/home/git/backup.git remote add origin
    git --work-tree=/home/backup --git-dir=/home/git/backup.git checkout -f
    # git --work-tree=/home/backup --git-dir=/home/git/backup.git checkout -b master # 创建切换分支
    git --work-tree=/home/backup --git-dir=/home/git/backup.git push origin master # 提交代码至分支
  • Esc 键退出编辑模式,输入:wq 保存退出。(先输入,然后输入wq回车)

  • 修改文件权限,使得其可执行。

    $ chmod +x /home/git/backup.git/hooks/post-receive
  • 博客根目录_config下增加(因为服务器没有分支,默认是master,使用backup钩子)

    deploy:
        type: git
        repo: root@***(服务器ip,内网外网都行):/home/git/backup.git    #仓库地址
        branch: master    #分支

  • 备份hexo backup(使用 Hexo-Git-Backup 插件)

    $ hexo clean
    $ hexo g
    $ hexo b

这个地方走了不少弯路,因为backup阶段每次都提示错误:

fatal: 'xxx' does not appear to be a git repository
fatal: Could not read from remote repository.

我通过搜索fatal-does-not-appear-to-be-a-git-repository找到解决思路,用Git命令自动备份。详细参见HEXO博客实现自动备份3

  • 安装 shelljs 模块

    $ npm install --save shelljs
  • 编写自动备份脚本:主题目录下scripts文件夹下新建一个js文件,文件名随意取,例如update.js

require('shelljs/global');
try {
    // hexo.on('deployAfter', function() {         //当deploy完成后执行备份
    hexo.on('backupAfter', function() {            //当backup完成后执行备份
        run();
    });
} catch (e) {
    console.log("产生了一个错误<( ̄3 ̄)> !,错误详情为:" + e.toString());
}
function run() {
    if (!which('git')) {
        echo('Sorry, this script requires git');
        exit(1);
    } else {
        echo("======================Auto Backup Begin===========================");
        cd('XXXXXXX');    //此处修改为Hexo根目录路径
        if (exec('git add .').code !== 0) {
            echo('Error: Git add failed');
            exit(1);
        }
        if (exec('git commit -m "Form auto backup script\'s commit"').code !== 0) {
            if (exec('git remote add origin your_user_name@HostIP:/home/git/backup.git').code !== 0){       //修改访问服务器方式
                if (exec('git push origin master').code !== 0) {
                    echo('Error: Git push failed');
                    exit(1);
                }
            } else {
                echo('Error: Git commit failed');
                exit(1);
            }
        }
        if (exec('git push origin master').code !== 0) {
            echo('Error: Git push failed');
            exit(1);
        }
        echo("==================Auto Backup Complete============================")
    }
}

注意:

  • Hexo根目录或在主题目录下的scripts文件夹js在启动时就会自动载入,因此建议放在主题目录下,避免不必要的问题,例如Blog/themes/fluid/scripts/update.js
  • backup.js是在hexo backup运行后backupAfter自动触发的,因此可以在其他仓库备份(如githubcoding)后实现服务器的自动备份。
  • git远程仓库在服务器,所以push在服务器端的home/git/backup.gitpost-receive钩子中。
  • 由于设定了git免密设置,因此使用backup.git操作不需要重复的输入密码。

_config.yml下设置备份配置。注意:backup下不要有服务器的repo,因为在scriptsbackup.js已实现git push

backup:
    type: git
    message: 'backup updata: {{now("YYYY-MM-DD HH/mm/ss")}}'
    ## theme: fluid #主题
    repo: #XXX为用户地址或IP地址
        github: git@github.com:XXX.github.io.git,backup
        coding: git@e.coding.net:XXX.git,backup
        ## hexo: root@XXX:/home/git/backup.git,master
再来一波四连😄
$ hexo clean 
$ hexo g 
$ hexo d 
$ hexo b

得到

$ hexo b
INFO  Start backup: git
The file will have its original line endings in your working directory
[master 79b18cc] backup updata: XXXX
 2 files changed, 143 insertions(+), 4 deletions(-)
Branch 'master' set up to track remote branch 'backup' from 'github'.
To github.com:XXXXXX
   89e022d..79b18cc  master -> backup
Branch 'master' set up to track remote branch 'backup' from 'coding'.
To e.coding.net:XXXXXX
   89e022d..79b18cc  master -> backup
INFO  Backup done: git
======================Auto Backup Begin===========================
On branch master
Your branch is up to date with 'coding/backup'.

nothing to commit, working tree clean
fatal: remote origin already exists.
remote: usage: git remote add [<options>] <name> <url>
remote:
remote:     -f, --fetch           fetch the remote branches
remote:     --tags                import all tags and associated objects when fetching
remote:                           or do not fetch any tag at all (--no-tags)    
remote:     -t, --track <branch>  branch(es) to track
remote:     -m, --master <branch>
remote:                           master branch
remote:     --mirror[=(push|fetch)]
remote:                           set up remote as a mirror to push to or fetch from
remote:
remote: fatal: 'origin' does not appear to be a git repository
remote: fatal: Could not read from remote repository.
remote:
remote: Please make sure you have the correct access rights
remote: and the repository exists.
remote: fatal: not a git repository (or any of the parent directories): .git    
To XXXXXX:/home/git/backup.git
   89e022d..79b18cc  master -> master
Everything up-to-date
==================Auto Backup Complete============================

服务器的文件夹/home/backup下可看到Hexo backup的备份文件。同时,文件夹/home/hexohexo deploy的部署文件,通过Nginx提供 Web 服务。这就实现了服务器部署和备份的自动化操作。

Tips:如果遇到程序没有报错但文件夹上传失败时,可以手动删除Hexo根目录下的.deploy_git 文件夹,再重新部署和备份。

数学公式

在此补充一下之前公式不显示的问题。虽然Fluid主题支持LaTeX 数学公式,但是需要手动操作,而且我按照教程开启本功能mathjax没有成功,即公式在网页里并没有被渲染和转换。通过网上查找,发现解决这类问题的思路主要是换渲染引擎4,例如pandocmathjaxkatex。我目前使用mathjax,操作如下:

  • 卸载默认引擎,并安装这个新的渲染引擎

    $ npm uninstall hexo-renderer-marked --save 
    $ npm install hexo-renderer-kramed --save

  • 修改/node_modules/hexo-renderer-kramed/lib/renderer.js

    // Change inline math rule
    function formatText(text) {
      // Fit kramed's rule: $$ + \1 + $$
      // 直接返回text
      // return text.replace(/`\$(.*?)\$`/g, '$$$$$1$$$$');
      return text;
    }

  • 修改hexo的渲染源码/node_modules/kramed/lib/rules/inline.js

    // 去掉`\\`的额外转义,第11行,将其修改为
    // escape: /^\\([\\`*{}\[\]()# +\-.!_>])/, 
    escape: /^\\([`*{}\[\]()# +\-.!_>])/,
    // 将em标签对应的符号中,去掉`_`,第20行,将其修改为
    // em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,    
    em: /^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
  • 停止使用 hexo-math,安装 hexo-renderer-mathjax

    $ npm uninstall hexo-math --save
    // 不知道是不是必要的
    $ npm install hexo-renderer-mathjax --save
  • 更新 MathjaxCDN 链接,打开/node_modules/hexo-renderer-mathjax/mathjax.html,在最后一行添加js:

    • 网上推荐的上面这个,但我使用失败了
    // <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML"></script>
    • 推荐下面这个,亲测可行,不过偶尔出问题,需要多部署几次就ok
    <script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_CHTML"></script>
    • 更新于2020年6月6日:如果有人看到这,可以注意下MathJax.js版本已经到3.0.5了,参照mathjax文档,那么现在的上面的一步可以自行修改,如果控制台报错可以到mathjax CDN files下找到合适的js代替
    <script id="MathJax-script" async
      src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg-full.js">
    </script>
  • 按照Fluid快速开始,需要修改主题配置,打开/source/_data/fluid_config.yml 文件

    post:
      math:  
        enable: true  
        specific: false   
        engine: mathjax
  • 在根目录下修改_config.yml,添加

    mathjax: true
  • Front-matter中打开MathJax

    ---
      layout: post
      title: title
      date: date
      categories: 
      - categories
      tags: 
      - tags1
      - tags2
      mathjax: true
    ---
  • 显示数学公式

    # 不空行会出bug
    $$\Sigma({n} ; {p})=\left\{\left(\zeta_{1}, \ldots, \zeta_{r}\right) \in \mathbb{C}^{n_{1}} \times \cdots \times \mathbb{C}^{n_{r}}: \sum_{k=1}^{r}\left\|{\zeta}_{k}\right\|^{2 p_{k}} < 1\right\}$$

\[ \Sigma({n} ; {p})=\left\{\left(\zeta_{1}, \ldots, \zeta_{r}\right) \in \mathbb{C}^{n_{1}} \times \cdots \times \mathbb{C}^{n_{r}}: \sum_{k=1}^{r}\left\|{\zeta}_{k}\right\|^{2 p_{k}} < 1\right\} \]

因为hexo-renderer-kramedhexo-renderer-marked均不支持emoji 功能,使用:smile: :blush: :smiley: :smirk:在Typora可以正常显示表情,在网页上显示的是:smile: :blush: :smiley: :smirk:,因此,可以直接复制emoji表情😄😊😃😏。

经过强哥 zkqiang 提醒,需要额外使用插件hexo-filter-github-emojis来支持hexoemoji

$ npm install hexo-filter-github-emojis --save

在根目录下_config.yml添加配置

githubEmojis:
  enable: true
  className: github-emoji
  inject: true
  styles:
  customEmojis:

正文markdown用如下格式使用 emoji

# 不空行会出bug
{% github_emoji emoji %}

正如上面所说,传统的:emoji:仍然不能正确显示表情,如:tada: 得到:tada:,而该插件通过带入tada,即🎉(github_emoji tada)可得到 🎉 ,其他调用格式可以看hexo-filter-github-emojis官方文档

p.s.标记这些emoji会有小彩蛋在PC浏览器上标记表情会变。

p.p.s.hexo-filter-github-emojis仅适用于hexo博客。

一键三连

前面提到的在根目录下使用Git Bash Here输入下面指令有些繁琐。

$ hexo clean && hexo g && hexo d && hexo b

现在用.bat文件简化,可以分别保存。其中第四行的地址为根目录。

:: 一键预览
@echo on
D:
cd D:\github\Hexo-Blog
hexo clean && hexo g && hexo s
:: 一键部署
@echo on
D:
cd D:\github\Hexo-Blog
hexo clean && hexo g && hexo d
:: 一键部署+备份
@echo on
D:
cd D:\github\Hexo-Blog
hexo clean && hexo g && hexo d && hexo b

一键预览的窗口支持实时修改实时显示,即文档修改保存后,刷新可得修改后的预览页面。如果做到ssh免密登入,部署与备份也能一键完成。

最后需要强调一点,免密会带来安全隐患,部署和备份文件最好设置为私密

参考

- [1] Hexo博客部署到腾讯云服务器

- [2] 使用Git+Hooks实现Hexo站点自动部署到CentOS服务器上

- [3] HEXO博客实现自动备份

- [4] 如何在 hexo 中支持 Mathjax?