0x0A - Git Everything!在自己的服务器上搭建 Git 还有 pages 服务
从原因开始
使用别人搭建好的 Pages 服务当然可以很轻松的做到静态页面建站。
但是不管是从自由性来说还是后续扩展性上来说,都不如自己建站来的安心放心。
Github pages 受限于网络,假如是从国内读取的话,很有可能没法流畅加载 (CDN 也并不流畅)
而近期 Gitee Pages 也因为网络整治,没有办法提供正常的服务。
那怎么办呢?一切不如自己动手丰衣足食!
从零开始,搭建我们自己的 Pages 服务。
为其赋名:Shigure Pages
Shigure Pages
那么 Pages 服务大致分为两大块:
- Git 服务,或者说,需要一个仓库以供网页上传。
- nginx 服务,用以搭建简单的 web 服务。
我们需要通过 Git 仓库的管理功能,利用 hooks 脚本更新 nginx 指向的文件。
Git 服务
和 Github pages 、 Gitee Pages 一样,我们需要有一个云上的仓库来存放我们导出的静态页面。
搭建 git 服务
搭建 git 服务相对简单:
首先我们增加一个 git 的用户组,还有一个名叫 git 的用户:
1 | groupadd git |
接着我们切换到 git 用户,并且在 /home/git
文件夹下新建这么几个文件和文件夹:
1 | su git |
请在 .ssh/authorized_keys
配置 git 的 SSH key,不明白如何配置 SSH key 的请往下面看。
之后,我们继续操作,添加一个 git 仓库:
1 | cd gitrepo |
这个仓库就是我们想要的仓库了,而仓库的地址为 git@your.ip.address:~/gitrepo/sample.git
。
接着只需要按部就班,按照 git 的方式推送即可。
其实这就是一个简易的 git 平台了,后续只要像这样推送更新,就可以维护好一个不错的自定义 git 平台。
创建 SSH key 密钥对
首先找到你希望连接的终端,例如你希望用你的某台 Windows 10 系统电脑往这个仓库推送代码。
那么我们直接打开终端(Powershell,CMD 均可)
直接运行下面的命令,保持默认即可
1 | ssh-keygen |
你可以在 C:\Users\Your_Name\.ssh
里找到两个文件:id_rsa
,id_rsa.pub
,
右键用记事本打开 id_rsa.pub
,并把里面的内容加在服务器 /home/git/.ssh/authorized_keys
中。
这样,你就可以用上面的地址 push git 仓库了。
Nginx 服务
Nginx 是一个轻便的 web 服务框架,安装和使用都非常方便。
1 | sudo apt-get update |
然后把配置文件写成以下这个样子:
1 | # 删除所有内容,将以下内容写入nginx.conf |
然后我们新建一个用来存放网页的文件夹并赋予权限:
1 | mkdir -p /home/git/blog-site/www |
为了让 nginx 可以读取到文件,我们把下面这个用户添加进 git 用户组并赋予权限:
1 | usermod -a -G git www |
最后,刷新一下配置:
1 | nginx -s reload |
至此 nginx 搭建完毕。
注:此部分教程参考自 这个链接,部分内容修改,请酌情查看。
Git Hooks
为了要让 Git 仓库更新时触发 pages 的更新,我们需要更改一下 Git Hooks 脚本的配置。
1 | su git |
可以看到这下面有很多可执行的脚本。
那么其实 Git Hooks 的功能十分丰富,具体的话可以看 这里 来了解更多的 hooks 原理。
我们需要用到的是 post-receive
hook:
1 | vi post-receive |
把下面的内容添加到文件中,
注意,每个人的配置不同需求不同,请根据自己的需求进行修改。
我这边使用 Hexo
建站,目录结构比较单一
1 |
|
至此,一切就绪。