利用 GitHub Webhooks 自動更新 Hexo
每次寫完東西,還得用Hexo發布,換個環境還得重新搭建hexo,太不優雅。所以就用github webhooks來自動發布。
用到的東西有:vps,nginx+lua+shell
- 首先在vps上搭建hexo環境。
- 你的github page repository得有兩個分支。比如說master用來作為public訪問,code用來存hexo環境。在vps上clone下來,checkout到code分支。
- 安裝在lua mode的nginx。我直接用 openresty
- 在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
- hexo.lua,hexo.sh最好不要放在用戶目錄,因為nginx的worker用戶是www(centos),可能會沒權限,詳見這里https://github.com/smallnewer/bugs/issues/64
- git deploy用ssh key,這樣就不用輸密碼了。我之前寫過教程.但是這里還可能會出現權限問題,因為一般用ssh-keygen生成的key是放在當前用戶目錄下的,而 www根本訪問不到。我的第一種做法是將nginx的user改為用戶,簡單省事,而我直接用root登的,安全隱患太大。后來新建了/home/www/.ssh目錄,并將id_rsa拷過去。感覺還不是很優雅,后面看看有沒有更好的方案。
- 有問題看nginx的錯誤日志
一切順利的話,之后只要在本地寫完文章,push到code分支,就可以自動發布了。
Have fun !
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!