在vps上搭建hexo博客


cheerful-close-up-coffee

最近更換了服務器,需要把自己的Hexo Next重新部署到新服務器上,本文記錄一下在vps上搭建hexo博客的過程。

在vps上搭建hexo博客需要下面這些工具:

  1. Nginx: 用於博客展示
  2. SSH:用於Git 推送
  3. 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
  1. 注釋如下行:
exec git update-server-info
  1. 添加如下代碼:
git --work-tree="靜態文件VPS存放目錄" --git-dir="剛才新建的VPS git地址" checkout -f
例:
git --work-tree=/home/hexo/blog --git-dir=/home/hexo/blog.git checkout -f

例:
post-update

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

大功告成

遇到的問題總結

  1. 如果無法推送到vps,請檢查hexo用戶是否有權限操作所需目錄
  2. 關於 nginx root 403 問題: 在我配置nginx碰到一個403問題,改了文件權限還是403,后來發現是nginx.conf中 user默認設置錯了,把 user nginx改成user root 就好了。
  3. deploy成功之后無法訪問
    1. 查看vps靜態目錄是否有html文件,沒有就是Git推送問題
    2. 查看Nginx配置是否成功(通過systemctl status nginx.service -l查看詳細錯誤)

參考文檔:

  1. https://www.worldhello.net/gotgit/08-git-misc/070-hooks-and-templates.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM