新建一個名爲 y0ngb1n.github.io
的倉庫,格式爲:<username>.github.io
。html
GitHub 爲咱們提供了一個二級域名 <username>.github.io
,若是咱們爲本身的某個項目開啓了 GitHub Pages 功能後,咱們可使用 http(s)://<username>.github.io/<projectname>
進行訪問,這樣咱們能夠爲每一個項目添加上項目展現的 Pages;當咱們「新建一個名爲 <username>.github.io
—本身對應的二級域名—的倉庫」時,GitHub 會將該倉庫路由爲咱們的我的主頁,可以使用 http(s)://<username>.github.io
進行訪問。git
按照倉庫頁面上的提示進行操做便可:github
# 初始化 git 倉庫 git init # 進行版本控制 git add . # 提交 git commit -m ":tada: init hexo" # 添加遠程倉庫(GitHub)地址 git remote add origin https://github.com/y0ngb1n/y0ngb1n.github.io.git # 推送代碼 git push -u origin master
過程會提示輸入賬號密碼,推送成功後,刷新倉庫頁面後便可看到咱們提交的源碼了。npm
先使用 Hexo 進行編譯:緩存
# 清除緩存,可選 hexo clean # 編譯 hexo g
而後使用 hexo-deployer-git
插件進行部署:bash
# 安裝插件 npm install hexo-deployer-git
修改 _config.yml
:hexo
deploy: type: git repo: git@github.com:y0ngb1n/y0ngb1n.github.io.git branch: gh-pages
這裏使用 SSH
協議,由於只能走 Git 協議,走 HTTPS 協議會報錯;關於 SSH
的請參考「Connecting to GitHub with SSH」、「SSH 原理與運用(一):遠程登陸」。ssh
而後進行部署:gitlab
hexo d
部署成功後,會自動在遠程倉庫建立 gh-pages
分支。spa
本來是想部署 gh-pages
分支的,結果只能部署 master
分支,因爲咱們的 master
分支上沒有 index.html
文件,因此訪問主頁時出現了 404;
經驗證:是因爲咱們的倉庫使用了二級域名的方式,GitHub Pages 只能部署 master
分支,且不能選擇,若是把名字改成別的(如 blog
),此時就能選擇部署哪一個分支了。
我想到的有兩個解決方案:
調整分支策略:
master
:編譯後的靜態資源source
:博客源碼修改倉庫名(如 blog
):
/blog
後綴進行訪問(能夠自定義域名解決)這裏我選擇方案 1(調整分支策略):
# 查看全部分支 $ git branch -a ls * master remotes/origin/master # *先在倉庫設置中將 gh-pages 設置爲默認分支(不然沒法刪除 master 分支) # 重命名本地 master 分支爲 source $ git branch -m master source # 刪除遠程 master 分支 $ git push --delete origin master To github.com:y0ngb1n/y0ngb1n.github.io.git - [deleted] master # 上傳新的 source 分支 $ git push origin source To github.com:y0ngb1n/y0ngb1n.github.io.git * [new branch] source -> source
而後修改 _config.yml
,將編譯後的靜態部署至 master
分支:
deploy: type: git repo: git@github.com:y0ngb1n/y0ngb1n.github.io.git branch: master
修改完成後,執行 hexo d
進行編譯部署,直到遠程倉庫出現新的 master
分支,命令以下:
$ hexo d INFO Deploying: git INFO Clearing .deploy_git folder... INFO Copying files from public folder... INFO Copying files from extend dirs... On branch master nothing to commit, working tree clean remote: remote: Create a pull request for 'master' on GitHub by visiting: remote: https://github.com/y0ngb1n/y0ngb1n.github.io/pull/new/master remote: Branch 'master' set up to track remote branch 'master' from 'git@github.com:y0ngb1n/y0ngb1n.github.io.git'. To github.com:y0ngb1n/y0ngb1n.github.io.git * [new branch] HEAD -> master INFO Deploy done: git
此時 github-pages
監測到 master
分支有更新,會更新部署,此時訪問 https://y0ngb1n.github.io/ 終於看到了期待以久的 Hexo 博客頁面。
由於咱們調整了分支策略,因此此時 source
分支纔是咱們的主分支了,在設置中把 source
設置爲默認分支,而後再把 gh-pages
分支從遠程倉庫中刪除掉。
# 刪除遠程 gh-pages 分支 $ git push --delete origin gh-pages To github.com:y0ngb1n/y0ngb1n.github.io.git - [deleted] gh-pages
至此就大功告成啦!🎉🎉🎉
只有 GitHub 可能免費託管嗎?
固然不止啦,其它平臺也有提供這樣的 Pages 功能,如: