前言

自从再Github上部署完博客,使用了一段时间之后非常喜欢,干脆就把我之前的 Typecho 换成了 Hexo。Hexo可以一条命令直接发布并且部署,可以说是非常方便。但是 Github + Cloudflare 对于国内的访问非常卡顿(,所以我就一直在想如何在部署的时候直接发布到国内的服务器。我的设想是 本地→GitHub→VPS

软件准备

  1. Web Server
  2. Git

在 VPS 上搭建Git Server

我这边选用 Centos 来搭建Git Server。ArchLinux我试过也是可行的,其他系统可以按照教程自行尝试下。

安装Git

首先需要安装Git,可以用yum源进行安装

1
sudo yum install -y git

接下来我们检查是否安装成功

1
2
[root@VM-0-17-centos ~]# git version
git version 1.8.3.1

增加运行Git的用户

1
useradd git 

这里要为他设置一个密码这里可以随便设置

1
passwd git

Git 仓库目录

创建完用户之后我们还需要给他创建一个仓库目录来存放我们的项目
在这里我放在 /git/repo

1
2
sudo mkdir -p /git/repo
cd /git/repo

初始化仓库

1
git init --bare xxx.git

执行ls可以查看有没有创建成功

设置权限

回到/git目录底下来设置repo文件夹的权限,这一步是为了直接把 repo 目录和子目录的用户和用户组都指向 git ( 如果没有这一步无法上传会提示权限不足

1
chown -R git:git reponame.git

测试

用法是git clone 用户名@你的服务器ip:仓库路径

1
git clone git@ip:/git/repo/xxx.git 

如果他提示warning: You appear to have cloned an empty repository.就意味着你的 Git Server已经搭建成功了,但是我们是通过密码登录的,这不是我们想要的效果,所以我们要让这个 Git 用户使用私钥登录

添加私钥

我们切换到root用户 然后到/home/git目录下然后进入到.ssh目录下创建一个authorized_keys,在 authorized_keys 里面写入你的私钥 你的 Git Server 就完成了

1
2
3
4
su root
cd /home/git/.ssh
touch authorized_keys
nano authorized_keys

同步

右键 -> Git Bash Here,设置用户名和邮箱

1
2
git config --global user.name "用户名" 
git config --global user.email "邮箱"

本地博客测试成功后,就是上传到 GitHub 部署

安装 hexo-deployer-git:

1
npm install hexo-deployer-git --save

修改 _config.yml

1
2
3
4
deploy:
- type: git
repository: git@github.com:用户名/用户名.github.io.git
branch: master

完成后就可以运行 hexo clean & hexo g & hexo d 将网站上传到 GitHub。

VPS

VPS 这里我选择使用 Git Hooks 实现博客的更新,VPS可以配置 Git Hooks,将文件同步到站点目录

配置Git Hooks

我们先切换到root用户,然后到你存放git仓库的目录,我这里叫xxx.git,可以将你的仓库名字替代到xxx里面

1
2
3
4
su root
cd /git/repo/xxx.git/hooks
touch post-receive
nano post-receive

在 nano 中输入以下代码后保存退出

1
2
3
4
5
6
7
8
#!/bin/bash
GIT_REPO=/git/repo/xxx.git
TMP_GIT_CLONE=/tmp/hexo
PUBLIC_WWW=/www/wwwroot/nekoyyang.eu.org
rm -rf ${TMP_GIT_CLONE}
git clone $GIT_REPO $TMP_GIT_CLONE
rm -rf ${PUBLIC_WWW}/*
cp -rf ${TMP_GIT_CLONE}/* ${PUBLIC_WWW}

然后再给予这个脚本执行权限

1
chmod +x post-receive  

本机配置

进入hexo博客文件夹,打开_config.yml,修改deploy选项

1
2
3
4
5
6
7
deploy:
- type: git
repository: git@github.com:NekoYyang/NekoYyang.github.io.git
branch: master
- type: git
repository: git@vps ip:xxx.git:/git/resp/xxx.git
branch: master

运行hexo clean & hexo g & hexo d 如果一切正常 如果文件已经被成功推到了 Blog 的仓库里,到现在成功部署到VPS上

网页部署

我这边使用 BTPanel 方法很简单就不再演示了