每次写完东西,还得用Hexo发布,换个环境还得重新搭建hexo,太不优雅。所以就用github webhooks来自动发布。

用到的东西有:vps,nginx+lua+shell

  1. 首先在vps上搭建hexo环境。
  2. 你的github page repository得有两个分支。比如说master用来作为public访问,code用来存hexo环境。在vps上clone下来,checkout到code分支
    (这里有个安全问题,code分支中__config.yml可能会暴露,更合适的做法是用另一个私有项目来托管hexo环境(即这里的code分支),page页则在公开项目中)
  3. 安装在lua mode的nginx。我直接用openresty
  4. 在nginx加个server,如下:
server {
    listen       80;
    server_name  example.com or ip;

    lua_code_cache on;

    location /hexo/github {
        content_by_lua_file /var/www/hexo/hexo.lua;
    }
}         

5.hexo.lua,前面是验证,最后是执行hexo.sh

local signature = ngx.req.get_headers()["X-Hub-Signature"]
local key = "yourSecretkey"
if signature == nil then
    return ngx.exit(404)
end
ngx.req.read_body()
local t = {}
for k, v in string.gmatch(signature, "(%w+)=(%w+)") do
    t[k] = v
end
local str = require "resty.string"
local digest = ngx.hmac_sha1(key, ngx.req.get_body_data())
if not str.to_hex(digest) == t["sha1"] then
    return ngx.exit(404)
end
os.execute("bash /var/www/hexo.sh");
ngx.say("OK")
ngx.exit(200)

6.hexo.sh,修改相应路径

#! /bin/bash

blog_dir=/path/to/git/repository
git=/usr/bin/git
branch=code
hexo=/usr/local/bin/hexo

cd $blog_dir
$git reset --hard origin/$branch
$git clean -f
$git pull

$hexo clean
$hexo d -g

echo "success"	

7.重启nginx

8.在github设置webhooks,Secret填hexo.lua中的key.

tips

  1. hexo.lua,hexo.sh最好不要放在用户目录,因为nginx的worker用户是www(centos),可能会没权限,详见这里https://github.com/smallnewer/bugs/issues/64
  2. git deploy用ssh key,这样就不用输密码了。我之前写过教程.但是这里还可能会出现权限问题,因为一般用ssh-keygen生成的key是放在当前用户目录下的,而www根本访问不到。我的第一种做法是将nginx的user改为用户,简单省事,而我直接用root登的,安全隐患太大。后来新建了/home/www/.ssh目录,并将id_rsa拷过去。感觉还不是很优雅,后面看看有没有更好的方案。
  3. 有问题看nginx的错误日志

一切顺利的话,之后只要在本地写完文章,push到code分支,就可以自动发布了。

Have fun !