最近更換了服務器,需要把自己的Hexo Next重新部署到新服務器上,本文記錄一下在vps上搭建hexo博客的過程。
在vps上搭建hexo博客需要下面這些工具:
- Nginx: 用於博客展示
- SSH:用於Git 推送
- Git: 用於將生成的靜態文件推送到vps上
本文服務器環境為CentOS 7.6
整體流程為:
設置SSH登錄
想要完成Git推送,首先得設置SSH登錄。過程如下:
# 添加hexo用戶
adduser hexo
# 切換到hexo用戶
su 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/authorized_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
# 新建blog目錄存放hexo靜態文件
mkdir /home/hexo/blog
# 使用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端口
listen 80 default_server;
listen [::]:80 default_server;
# 修改server_name為自己之前注冊好的域名,沒有就不用更改
server_name morethink.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配置是否成功(通過
systemctl status nginx.service -l
查看詳細錯誤)
參考文檔: