在vps上搭建hexo部落格
最近更換了伺服器,需要把自己的Hexo Next重新部署到新伺服器上,本文記錄一下在vps上搭建hexo部落格的過程。
在vps上搭建hexo部落格需要下面這些工具:
- Nginx: 用於部落格展示
- SSH:用於Git 推送
- Git: 用於將生成的靜態檔案推送到vps上
本文伺服器環境為CentOS 7.6
整體流程為:
設定SSH登入
想要完成Git推送,首先得設定SSH登入。過程如下:
# 新增hexo使用者 adduser hexo # 切換到hexo使用者目錄 cd /home/hexo # 建立.ssh資料夾 mkdir .ssh # 建立authorized_keys檔案並編輯 vim .ssh/authorized_keys # 如果你還沒有生成公鑰,那麼首先在本地電腦中執行 cat ~/.ssh/id_rsa.pub | pbcopy生成公鑰 # 再將公鑰複製貼上到authorized_keys # 儲存關閉authorized_keys後,修改相應許可權 chmod 600 .ssh/authorzied_keys chmod 700 .ssh
測試是否設定成功:
ssh -v hexo@伺服器ip
Git
安裝Git
yum install git
配置post-update鉤子
Git的鉤子指令碼位於版本庫.git/hooks目錄下,當Git執行特定操作時會呼叫特定的鉤子指令碼。當版本庫通過git init或者git clone建立時,會在.git/hooks目錄下建立示例指令碼,使用者可以參照示例指令碼的寫法開發適合的鉤子指令碼。
鉤子指令碼要設定為可執行,並使用特定的名稱。Git提供的示例指令碼都帶有.sample副檔名,是為了防止被意外執行。如果需要啟用相應的鉤子指令碼,需要對其重新命名(去掉.sample副檔名)。
post-update
該鉤子指令碼由遠端版本庫的git receive-pack命令呼叫。當從本地版本庫完成一個推送之後,即當所有引用都更新完畢後,在遠端伺服器上該鉤子指令碼被觸發執行。
因此我們需要配置post-update鉤子以便可以及時更新我們在VPS上存放Hexo 靜態檔案的目錄。
# 回到hexo目錄 cd /home/hexo # 變成hexo使用者 su hexo # 使用hexo使用者建立git裸倉庫,以blog.git為例 git init --bare blog.git # 進入鉤子資料夾hooks cd blog.git/hooks/ # 啟用post-update mv post-update.sample post-update # 新增執行許可權 chmod +x post-update # 配置post-update vim post-update
- 註釋如下行:
exec git update-server-info
- 新增如下程式碼:
git --work-tree="靜態檔案VPS存放目錄" --git-dir="剛才新建的VPS git地址" checkout -f 例: git --work-tree=/home/hexo/blog --git-dir=/home/hexo/blog.git checkout -f
例:

Nginx
安裝Nginx
yum install nginx
使用 nginx -v
檢視,顯示版本號則安裝成功。
Nginx配置
server { # 預設80埠 listen80 default_server; listen[::]:80 default_server; # 修改server_name為自己之前註冊好的域名,沒有就不用更改 server_namemorethink.cn; # 修改網站根目錄,在這裡存放你的Hexo靜態檔案,請自行選擇或建立目錄 root/home/hexo/blog; # 其他保持不變 # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } }
配置本地Hexo
找到本地Hexo部落格的站點配置檔案 _config.yml
,找到以下內容並修改:
deploy: type: git repo: hexo@你的伺服器IP:/home/git/blog.git branch: master
然後在根目錄執行以下命令:
hexo clean hexo g -d
遇到的問題總結
- 如果無法推送到vps,請檢查hexo使用者是否有許可權操作所需目錄
- 關於
nginx root 403
問題: 在我配置nginx碰到一個403問題,改了檔案許可權還是403,後來發現是nginx.conf中 user預設設定錯了,把user nginx
改成user root
就好了。 - deploy成功之後無法訪問
- 檢視vps靜態目錄是否有html檔案,沒有就是Git推送問題
- 檢視Nginx配置是否成功
參考文件:
- https://www.worldhello.net/gotgit/08-git-misc/070-hooks-and-templates.html