自建支持hexo的git服务器

我们一般使用github的pages功能来搭建我们的hexo blog,确实挺方便的,直接使用hexo d命令就可以提交文件到github,然后刷新一下就看到新页面了。还可以绑定我们的域名,甚至顶级域名。github还提供了CDN,所以访问速度也不错。
但是用别人总有不爽的地方,比如github有时候会被墙,提交速度很慢或者提交失败,虽然有了CDN,但是节点在澳大利亚,访问速度在晚上高峰时间不尽人意,不爽就折腾一下,于是就尝试使用国内的VPS来架设和github pages一样功能的服务器。

1.安装git server

手头有台百度云的vps,访问速度还不错,装的系统是ubuntu14 64位,先来安装git server。

1
2
3
4
apt-get update
apt-get upgrade
apt-get install git-core
git --verison

看到git version x.x.x,git server就装好了。

2.增加用户,初始化git仓库

不建议直接使用root用户,所以我们新增加一个用户和用户组,并为新用户建立home文件夹。

1
2
3
4
5
6
7
8
9
groupadd git
mkdir /home/blog
useradd -g git -d /home/blog blog
chown -R blog:git blog
su blog
cd /home/blog
git init --bare blog.git
su root
chown -R blog:git blog.git

当我们看到“Initialized empty Git repository in /home/blog/blog.git/”的时候,一个名为blog.git的裸库就建好了。

3.配置SSH免登陆

之前提交id_rsa.pub公钥给github之后我们就可以免输入账号密码来提交更新代码了,其实原理就是ssh免登陆,现在我们在自己的服务器上也要配置一下。

1
2
3
4
mkdir .ssh
cd .ssh
touch authorized_keys
cat /home/blog/id_rsa.pub > authorized_keys

这样就配置好了SSH免登陆,接下来我们试用一下我们的git server.

1
2
3
4
git clone ssh://blog@xxx.xxx.xxx.xxx/home/blog/blog.git
Cloning into 'blog'...
warning: You appear to have cloned an empty repository.
Checking connectivity... done.

已经成功免登陆clone了我们的blog.git仓库。

4.更改hexo的deploy设置

打开hexo根目录下的_config.yml文件,拉到最后,修改为:

1
2
3
4
deploy:
type: git
repository: ssh://blog@xxx.xxx.xxx.xxx/home/blog/blog.git
branch: master

修改好config文件时候,尝试发送hexo静态文件到服务器。

1
2
hexo clean
hexo d

正常情况下可以push文件到服务器。
现在问题来了,虽然文件push了但blog.git文件夹并没有看到我们的文件,该怎么呢?

5.建立git hook实现网站自动部署

现在的blog.git文件夹只是一个git裸库,只保存了一些git自己的文件,比如版本,配置。。。
那么我们需要一个钩子也就是hook来实现每次push自动把新内容部署到我们的网站目录。
例如我的博客放在和blog.git同级的blog目录,在之前我已经使用nginx或者apache或者我自己写的nodejs的静态服务器NSS为blog目录绑定了好域名,做好了访问的准备。
最后一步就是创建hook:

1
2
3
4
5
6
cd /home/blog/blog.git/hooks
cat > post-receive <<EOF
>#!/bin/bash
>git --work-tree=/home/blog/blog checkout -f
>EOF
chmod +x post-receive

创建好hook之后,再执行hexo clean和hexo d一次,然后打开域名,是不是看到我们的hexo blog了呢?
至此,就配置好了服务器,这个服务器和github pages有一样的功能,访问速度很快,不会被墙,最重要的是这是我们自己折腾出来的,成就感满满的啊。

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×