云服务器部署Hexo的简易指南

前言

官方文档写得很差,但必要时还是最好参考官方文档

本地准备

请确保已经安装 Node 和 Git

安装 Hexo

1
2
3
4
5
6
7
8
9
10
# 新建一个文件夹, 这里使用 ~/blog 演示
$ mkdir ~/blog
$ cd ~/blog
# 安装 Hexo
$ npm install -g hexo-cli
# 初始化 (名称随意)
$ hexo init blog
$ cd blog
# 安装 Hexo 依赖
$ npm install

安装完毕后可启动服务进行测试

1
$ hexo server

服务端准备

自行安装 Nginx

配置 Nginx

创建一个文件夹储存静态文件

1
$ mkdir -p /data/hexo

修改 Nginx 配置文件

配置文件可能存放在 /etc/nginx/,不同系统位置不同,请自行查看
修改 sites-enabled 目录下的 default 文件
root 项的内容指向刚刚创建的 /data/hexo,例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
server {
listen 80;
listen [::]:80;
server_name 公网IP;

location / {
root /data/hexo;
index index.html index.htm;
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}

若要配置 HTTPS,需准备 SSL 证书(后续更新个人非常喜欢的方案)

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
server {
listen 80;
listen [::]:80;
server_name 域名;

rewrite ^(.*)$ https://${server_name}$1 permanent;
}

server {
listen 443 ssl;
server_name 域名;

ssl_certificate 存放公钥的位置;
ssl_certificate_key 存放私钥的位置;

ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;

ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;

location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
root /data/hexo;
index index.html index.htm;
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}

启动 Nginx

1
$ sudo systemctl start nginx

配置 Git

1
2
3
4
5
6
# 创建git用户 (演示采用 Ubuntu 20.04)
$ adduser git
# 赋予 sudo 权限
$ usermod -aG sudo git
# 切换到 git 用户
$ su git

在家目录创建.ssh文件夹,存放公钥

1
$ mkdir ~/.ssh

本地 (不是服务器) 生成公钥和密钥

1
2
$ cd ~/.ssh
$ ssh-keygen

给私钥设置权限,执行以下指令:

1
2
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/id_rsa

复制 ~/.ssh/id_rsa.pub 中的内容
服务端 刚刚创建的 ~/.ssh 目录创建 authorized_keys 文件

1
2
3
4
5
# 自行进入文件粘贴公钥中的内容
$ touch ~/.ssh/authorized_keys
# 设置权限
$ chmod 600 ~/.ssh/authorized_keys
$ chmod 700 ~/.ssh

测试本地免密登录服务器

1
$ ssh -v [email protected](公网IP)

配置 Git 仓库

在服务器新建一个 Git 仓库,同时新建一个钩子文件

1
2
3
$ cd ~
$ git init --bare hexo.git
$ vim ~/hexo.git/hooks/post-receive

添加内容 git --work-tree=/data/hexo --git-dir=/home/git/hexo.git checkout -f
授予钩子文件可执行权限

1
2
$ chmod +x ~/hexo.git/hooks/post-receive
$ sudo chmod -R 777 /data/hexo

服务端配置完成

部署 Hexo 博客到服务端 Git 仓库

在本地计算机打开 Hexo 项目,修改 _config.yml 文件中的 deploy

1
2
3
deploy:
type: git
repo: git@公网ip:/home/git/hexo.git

如果更改了 ssh 端口

1
2
3
deploy:
type: git
repo: ssh://git@公网ip:端口/home/git/hexo.git

安装插件 hexo-deployer-githexo-server

1
2
3
4
5
# 用于将 Hexo 生成的静态文件推送到指定的 Git 仓库
$ npm install hexo-deployer-git --save

# 用于在本地启动一个 Hexo 服务器,方便在本地预览博客
$ npm install hexo-server

最后,让我们启动 Hexo

1
2
3
4
5
6
7
8
9
10
11
# 清除之前生成的静态文件
$ hexo clean

# 生成静态文件
$ hexo generate

# 部署到 Git 仓库
$ hexo deploy

# 可简化为
$ hexo clean && hexo g -d

云服务器部署Hexo的简易指南
http://www.cactily.me/2025/06/17/hexo-simple-deploy/
Author
Cactus
Posted on
June 17, 2025
Licensed under