Hexo+Github+VPS 同步方案

在 GitHub 部署完 Hexo, 使用了之后非常喜欢, 博主原来的博客是用 WordPress 搭建的, 众所周知的原因在 WordPress 上使用 MarkDown 写博客是十分的痛苦, 就算是使用插件也有从写到发布的烦恼, 所以干脆就把原来的 WordPress 换成了 Hexo. Hexo 可以直接用 MarkDown 写文章, 写完后只要一条命令就能发布, 可以说是非常的方便和畅快了.

博客搭建

前提

请确保 VPS 安装了下列程序:

  • Nginx
  • Git

这里假定已经安装完了, 我就不赘述一遍安装过程了.

开始搭建

在 Nginx 的站点上 clone 下在 Github 上托管的源码.进入站点所在的目录, 我的是/www/wwwroot/www.wuyinghao.cn, 然后把 GitHub 上的源码 clone 下来, 并且修改配置文件 server 下的 root 字段值修改为 clone 后的博客目录路径

server {
    listen 80;
	listen 443 ssl http2;
    server_name wuyinghao.cn www.wuyinghao.cn;
    index index.php index.html index.htm default.php default.htm default.html;
    root /www/wwwroot/www.wuyinghao.cn/Takuwy.github.io;
    }

我的博客在 GitHub 的仓库名是 Takuwy.github.io, 所以修改为

root /www/wwwroot/www.wuyinghao.cn/Takuwy.github.io;

根据情况把上面的换成自己的就可以了.

现在可以通过域名访问存放在 VPS 上的博客了, 但还没完, 如果我们写了新的文章执行 hexo g -d 时只会将文章同步到 GitHub 上 而在VPS上则没有同步.

同步

创建 git 仓库

创建 git 用户

adduser git

将 git 用户加到 root 用户组

gpasswd -a git sudo

创建 Git 仓库

su git
cd
mkdir blog.git
cd blog.git
git init --bare

变更 /www/wwwroot/www.wuyinghao.cn/Takuwy.github.io 目录拥有者为 git

chown git:git -R /www/wwwroot/www.wuyinghao.cn/Takuwy.github.io

SSH Key 配置

获取本地电脑 SSH Key

cat ~/.ssh/id_rsa.pub

添加 SSH Key

su git
cd
mkdir .ssh && cd .ssh
touch authorized_keys
vim authorized_keys

将 SSH Key 复制到 VPS 上的 authorized_keys 文件中

添加 Git hooks

编辑 post-receive 文件

su git
cd
cd blog.git/hooks
vim post-receive

输入下列内容

#!/bin/bash
GIT_REPO=/home/git/blog.git
TMP_GIT_CLONE=/tmp/blog
PUBLIC_WWW=/www/wwwroot/www.wuyinghao.cn/Takuwy.github.io
rm -rf ${TMP_GIT_CLONE}
git clone $GIT_REPO $TMP_GIT_CLONE
rm -rf ${PUBLIC_WWW}/*
cp -rf ${TMP_GIT_CLONE}/* ${PUBLIC_WWW}

/www/wwwroot/www.wuyinghao.cn/Takuwy.github.io 是我的网站路径, 换成你的

最后修改文件权限

chmod +x post-receive

Hexo 配置

修改本地电脑上的 _config.yml 文件, 添加刚创建的 blog.git 仓库

deploy:
  type: git
  repo: 
        github: git@github.com:Takuwy/Takuwy.github.io.git,main
        hexo: git@你的VPS公网IP:blog.git,master

这样就完成了, 之后执行 hexo -g d 命令时就可以一起同步在 GitHub 和 VPS 上了.