前言

原博客是使用Halo搭建,Halo太吃内存,导致VPS不堪重负,遂决定迁移博客到Hexo。

前置环境准备

VPS操作系统为Ubuntu Server 20.04

VPS安装git

VPS安装Nginx

Windows环境安装Git

Windows环境 已配置 ssh-keygen

配置VPS上的git

1
2
3
4
5
6
7
8
9
10
adduser git # 增加git用户

chmod 740 /etc/sudoers # 修改sudo权限
vim /etc/sudoers
--------------------------
# User privilege specification
root ALL=(ALL:ALL) ALL
---------------------------
# 在下面添加 git ALL=(ALL:ALL) ALL
chmod 440 /etc/sudoers # 改回权限

禁用git用户的shell权限

1
2
3
vim /etc/passwd
把git:x:1001:1001:***:/home/git:/bin/bash
修改为 git:x:1001:1001:***:/home/git:/bin/git-shell

初始化 git 仓库

1
2
3
4
cd /home/git                //切换到git用户目录
mkdir blog.git //创建git仓库文件夹,以blog.git为例
cd blog.git //进入仓库目录
git init --bare //使用--bare参数初始化为裸仓库,这样创建的仓库不包含工作区

配置 SSH-Key

1
2
3
4
cd /home/git                
mkdir .ssh
cd .ssh
vim authorized_keys # 将windows上的公钥复制的此文件内

修改目录权限

1
2
3
chown -R git.git /home/git/blog.git/
chown -R git.git /home/git/.ssh/
chown -R git.git /var/www/html/

配置 nginx(可选)

1
2
3
cd /etc/nginx/sites-available           
cp default default.bak
vim default
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
default
---------------------------------------
server {
listen 80 default; # 默认监听80端口
root /var/www/html;
server_name 18db.top, www.18db.top;
access_log /var/log/nginx/blog_access.log;
error_log /var/log/nginx/blog_error.log;
error_page 404 = /404.html;

location ~* ^.+\.(ico|gif|jpg|jpeg|png)$ {
root /var/www/html;
access_log off;
expires 1d;
}

location ~* ^.+\.(css|js|txt|xml|swf|wav)$ {
root /var/www/html;
access_log off;
expires 10m;
}

location / {
root /var/www/html;
if (-f $request_filename) {
rewrite ^/(.*)$ /$1 break;
}
}

location /nginx_status {
stub_status on;
access_log off;
}
}
1
2
3
systemctl restart nginx
systemctl enable nginx
systemctl status nginx

配置 Git Hooks 自动化

创建 post-receive 文件

1
2
cd /home/git/blog.git/hooks    
vim post-receive
1
2
3
4
5
6
7
8
9
10
post-receive 
----------------------------
GIT_REPO=/home/git/blog.git
TMP_GIT_CLONE=/tmp/blog
PUBLIC_WWW=/var/www/html

rm -rf ${TMP_GIT_CLONE}
git clone $GIT_REPO $TMP_GIT_CLONE
rm -rf ${PUBLIC_WWW}/*
cp -rf ${TMP_GIT_CLONE}/* ${PUBLIC_WWW}
1
chmod +x post-receive #赋予执行权限

在Windows上尝试免密登录VPS

1
2
# 在本地打开 Git Bash
ssh git@VPS_ip

修改本地博客根目录下的_config.yml 文件

1
2
3
4
5
6
# Deployment
## Docs: https://hexo.io/docs/deployment.html
deploy:
type: git
repo: git@VPS IP:/~/blog.git
branch: master