美文网首页
HEXO+Github+Next搭建博客

HEXO+Github+Next搭建博客

作者: HF_K | 来源:发表于2019-04-10 15:07 被阅读0次

前言

通过一个方式来整理和管理自己的知识,之前了解到可以通过 GitHub 托管静态网页,使用 Hexo 和 GitHub Pages 方便快捷地搭建个人博客网站,所以通过学习从零开始搭建、配置一个属于自己的博客网站。

注册 GitHub

  1. GitHub 是一个面向开源及私有软件项目的托管平台。首先需要注册一个账号并且创建仓库,作用是用来做博客的远程创库、域名、服务器之类的。

1.注意点:建立Repository,建立与你用户名对应的仓库,仓库名必须为[xxx.github.io],固定写法。

hexo_blog_githubNewR hexo_blog_githubSSH
  1. 配置SSH Keys,可以配置也也可以不配置。不配置的话以后每次对自己的博客有改动提交的时候就要手动输入账号密码,配置了每次访问就无需用户名和密码连接 GitHub 。
检查是否已经存在SSH Keys

打开终端,ls -al ~/.ssh查看结果,如果在.ssh目录下存在文件列表,说明已经存在 SSH keys 。

hexo_blog_githubCheckSSH

如果没有 public key ,生成 SSH;如果已经有了,直接配置即可。
输入ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
(将邮箱替换为你自己的地址)。然后一直回车下去,直到生成SSH Keys。

hexo_blog_githubCreateSSH

生成SSH Keys后,到GitHub中去配置SSH Keys
1. 找到id_rsa.pub中的public key,然后到GitHub Setting页面配置SSH。

hexo_blog_githubNEWSSHK

测试连接
输入ssh -T git@github.com

可能看到警告:
hexo_blog_github_1
hexo_blog_github_2

验证 fingerprint ,然后 type yes

然后,

hexo_blog_github_3

正式安装Hexo

Hexo是一款基于Node.js的静态博客框架,安装Hexo相当简单,可以参考官方文档

NodeGit都安装好后,可执行如下命令安装Hexo

$ npm install -g hexo-cli

如果没有安装NodeGit,以下均为 Mac 环境下。

# 使用 brew 安装 git
brew install git
# 可以使用 cURL 安装 nvm
$ curl https://raw.github.com/creationix/nvm/master/install.sh | sh
# 也可以 使用 Wget 安装 nvm
$ wget -qO- https://raw.github.com/creationix/nvm/master/install.sh | sh
# 使用最佳安装方式:nvm 安装 Node.js
$ nvm install stable

初始化

创建一个文件夹,如:BlogcdBlog里执行hexo init的。命令:

hexo init

生成静态页面

继续再Blog目录下执行如下命令,生成静态页面

hexo generate (hexo g  也可以)   

本地启动

启动本地服务,进行文章预览调试,命令:

hexo server (hexo s  也可以)  

访问

访问 本地配置,本地已经简单的设置好了,但是现在域名和服务器都是基于自己的电脑,接下来需要跟github进行关联。

配置Github

建立Repository

建立与你用户名对应的仓库,仓库名必须为your_user_name.github.io,固定写法 然后建立关联,我的Blog在本地/Users/leopard/Blog,Blog是我之前建的东西也全在这里面,有:

Blog 
 | 
 |-- _config.yml 
 |-- node_modules 
 |-- public 
 |-- source 
 |-- db.json    
 |-- package.json 
 |-- scaffolds 
 |-- themes  

现在我们需要_config.yml文件,来建立关联,命令:

vim _config.yml

翻到最下面,改成我这样子的,注意: : 后面要有空格

配置更目录下的 _config.yml文件

deploy:
 type: git
 repo: https://github.com/huangfangkai/huangfangkai.github.io.git
 branch: master

部署到 GitHub,前提是已经注册 GitHub,创建 username.github.io 仓库
安装 GitHub 依赖插件

$ npm install hexo-deployer-git --save

部署命令

# 部署,hexo deploy
$ hexo d
$ hexo d -g

访问个人主页
访问 username.github.io

部署步骤

每次部署的步骤,可按以下三步来进行。

hexo clean
hexo generate (hexo g)
hexo deploy (hexo d)

一些常用命令:

hexo new "postName" #新建文章
hexo new page "pageName" #新建页面
hexo generate #生成静态页面至public目录
hexo server #开启预览访问端口(默认端口4000,'ctrl + c'关闭server)
hexo deploy #将.deploy目录部署到GitHub
hexo help  #查看帮助
hexo version  #查看Hexo的版本

注意:这里需要注意的地方是:在执行 hexo g 命令时候,可能会出现以下 error,应该是 yarnnpm 冲突的依赖的问题,所以前面文章建议使用 yarn 管理包依赖

ERROR Plugin load failed: hexo-renderer-marked
Error: EISDIR: illegal operation on a directory, read
ERROR Plugin load failed: hexo-server
Error: EISDIR: illegal operation on a directory, read
ERROR Plugin load failed: hexo-renderer-stylus
Error: EISDIR: illegal operation on a directory, read

解决办法:先用 yarn 分别移除,再重新安装,如下

## 先移除
yarn remove hexo-renderer-marked

yarn remove hexo-renderer-stylus

yarn remove hexo-server

## 再安装
yarn add hexo-renderer-marked -S 

yarn add hexo-renderer-stylus -S

yarn add hexo-server -S

在执行 hexo g ,顺利执行

绑定域名

开始绑定自己的 域名 hfkstackoverflow.top
我们绑定域名之后,只支持 http 协议,这样我们在 Google 浏览器访问时,会有不安全标准,而且,很容易被插入广告,于是搞个 https,采用第三方服务 Netlify 来提供免费的SSL/TLS证书。

HTTP 绑定域名

设置域名解析规则

首先,我们需要去运行商,新增域名解析规则,如图

hexo_blog_yumingsetting

新增 CNAME 文件

配置好域名解析规则之后,还需要在项目的 .\source\ 路径下新增 CNAME 文件,输入内容 你的域名 ,如图

hexo_blog_CNAME

重新新生成文件,推送到GitHub

HTTPS 绑定域名

注册 Netlify 账号
首先,我们需要注册一个 Netlify 账号,可以选择用 GitHub 注册。

hexo_blog_Netlify

新增站点

点击如图按钮 New site from Git,来新增 站点

hexo_blog_NetlifyNewSite1

然后,点击如图按钮 GitHub

hexo_blog_NetlifyNewSite2

选择你的项目,比如我的 huangfangkai.github.io

点击 Deploy site

看到如图页面,表示成功,再点击 Site settings

hexo_blog_NetlifyNewSite3

再点击 Change site name 修改短名称,方便记忆

hexo_blog_NetlifyNewSite4

在自己的域名管理中设置 DNS ,我使用的是 阿里云 ,在管理界面添加如图规则

hexo_blog_NetlifyNewSite5

在点击 Domain management 下的 HTTPS ,按照步骤完成操作,稍等片刻,即可看到我们的 域名 已经上锁

主题

这里有大量的主题列表使用方法里面 都有详细的介绍,主要讲Next的配置。

主题安装参照Next主题介绍

安装 next 主题

    git clone https://github.com/iissnan/hexo-theme-next.git themes/next

更改配置文件

# Extensions
## Plugins: https://hexo.io/plugins/
## Themes: https://hexo.io/themes/
theme: next

站点配置

# Hexo Configuration  站点配置文件
## Docs: http://hexo.io/docs/configuration.html
## Source: https://github.com/hexojs/hexo/

# Site
title: HFK                             # 网站标题
subtitle: 欢迎到来~                     # 网站副标题
description:                           # 网站描述
author: HFK                            # 你的昵称
language: zh-Hans                      # 网站使用的语言(英文:en, 简体中文:zh-Hans,繁体中文:zh-tw)
email: huang0010445341@163.com
keywords: "iOS"
timezone: Asia/Shanghai                # 网站时区,用于生成页面时填充相关时间,默认使用电脑时区,一般不用改

# URL
## If your site is put in a subdirectory, set url as 'http://yoursite.com/child' and root as '/child/'
## 如果你的站点要放入子目录, 请将url设置为'http://yoursite.com/child' 并将根目录设置为'/child/'

url: http://www.hfkstackoverflow.top/        # 站点网址
root: /                                      # 网站根目录
permalink: :year/:month/:day/:title/         #文单的永久链接格式
permalink_defaults:                          # 永久链接中各部分的默认值

# Directory
# 目录
source_dir: source                           # 资源文件夹,这个文件夹用来存放博客内容
public_dir: public                           # 公共文件夹,这个文件夹用来存放生成的站点静态文件
tag_dir: tags                                # 标签文件夹
archive_dir: archives                        # 归档文件夹
category_dir: categories                     # 分类文件夹
code_dir: downloads/code                     # Include code文件夹
i18n_dir: :lang                              # 国际化文件夹,存放各种语言定义
skip_render:                                 # 跳过指定文件的渲染



# Writing
new_post_name: :title.md # File name of new posts                 # 新文章的文件名称
default_layout: post                                              # 预设布局
titlecase: false # Transform title into titlecase                 # 把标题转换为 title case
external_link: true # Open external links in new tab              # 在新标签中打开链接
filename_case: 0                                                  # 把文件名称转换为 (1) 小写或 (2) 大写
render_drafts: false                                              # 显示草稿
post_asset_folder: false                                          # 启动 Asset 文件夹
relative_link: false                                              # 把链接改为与根目录的相对位址
future: true                                                      # 显示未来的文章

highlight:                                                         # 代码块的设置                                                                                                                                                           
  enable: true                                                                                                                                                                                               
  auto_detect: true                                                                                                                                                                                          
  line_number: true                                                                                                                                                                                          
  tab_replace: ''

# Category & Tag
# 分类 & 标签
default_category: uncategorized                        # 默认分类
category_map:                                          # 分类别名
tag_map:                                               # 标签别名

# Archives
## 2: Enable pagination
## 1: Disable pagination
## 0: Fully Disable
archive: 1
category: 1
tag: 1

# Server
## Hexo uses Connect as a server
## You can customize the logger format as defined in
## http://www.senchalabs.org/connect/logger.html
port: 4000
server_ip: localhost
logger: false
logger_format: dev

# Date / Time format
# 日期 / 时间格式
## Hexo uses Moment.js to parse and display date
## You can customize the date format as defined in
## http://momentjs.com/docs/#/displaying/format/
date_format: YYYY-MM-DD       # 日期格式
time_format: HH:mm:ss         # 时间格式

# Pagination
# 分页
## 每页显示的文章量 (0 = 关闭分页功能)
## Set per_page to 0 to disable pagination
per_page: 8
pagination_dir: page

# Disqus
disqus_shortname:

# Extensions
## Plugins: https://github.com/hexojs/hexo/wiki/Plugins
## Themes: https://github.com/hexojs/hexo/wiki/Themes
# plugins:
#  - hexo-generator-feed
#  - hexo-generator-baidu-sitemap
#  - hexo-generator-sitemap

theme: next                 # 主题
exclude_generator:

# Deployment
## Docs: http://hexo.io/docs/deployment.html
#deploy:
#  type: git
#  repository: git@github.com:litten/litten.github.com.git
#  branch: master

deploy:
     type: git
     repo: https://github.com/huangfangkai/huangfangkai.github.io.git
     branch: master

Next配置

选择Scheme

进入主题配置文件,找到 Scheme 字段,Next有4种主题,选择自己喜欢的。

# Schemes  #主题
scheme: Muse
#scheme: Mist
#scheme: Pisces
#scheme: Gemini

设置菜单

1.进入主题配置文件,找到 menu 字段。

menu: #菜单 #菜单路径设置 如果hexo在二级目录放置要去掉/
  home: / || home
  tags: /tags/ || tags
  categories: /categories/ || th
  archives: /archives/ || archive
  about: /about/ || user
  #schedule: /schedule/ || calendar
  #sitemap: /sitemap.xml || sitemap
  #commonweal: /404/ || heartbeat

2.设定菜单项的图标,对应的字段是 menu_iconsicon nameFont Awesome 图标的名字。而 enable 可用于控制是否显示图标,你可以设置成 false 来去掉图标。

# Enable/Disable menu icons.
menu_icons:
  enable: true
  # Icon Mapping.
  home: home
  about: user
  categories: th
  tags: tags
  archives: archive
  commonweal: heartbeat

注意: 主题上面一些关于菜单标题可以到 next/languages/ 对应文件修改,如下图(改变中文):

hexo_blog_Next1

侧栏设置

进入主题配置文件,找到 sidebar 字段。

sidebar:
 # Sidebar Position, available value: left | right (only for Pisces | Gemini).
 #position: left  #靠左放置
 position: right  #靠右放置

 # Sidebar Display, available value (only for Muse | Mist):
 #  - post    expand on posts automatically. Default.
 #  - always  expand for all pages automatically
 #  - hide    expand only when click on the sidebar toggle icon.
 #  - remove  Totally remove sidebar including sidebar toggle.
 display: post             # 默认行为,在文章页面(拥有目录列表)时显示
 #display: always          #在所有页面中都显示
 #display: hide            #在所有页面中都隐藏(可以手动展开)
 #display: remove          #完全移除

头像设置

进入主题配置文件,找到 avatar 字段。

# Sidebar Avatar
# in theme directory(source/images): /images/avatar.gif
# in site  directory(source/uploads): /uploads/avatar.gif
avatar: /images/head.jpeg

添加「标签」页面

hexo new page tags

修改站点目录下 source/tags/index.md 文件如下:

hexo_blog_Next2

添加「分类」页面

hexo new page categories

修改站点目录下 source/categories/index.md 文件如下:

hexo_blog_Next3

腾讯公益404页面

腾讯公益404页面,寻找丢失儿童,让大家一起关注此项公益事业!效果如 http://www.ixirong.com/404.html

使用方法,新建 404.html 页面,放到主题的 source 目录下,内容如下:

<!DOCTYPE HTML>
<html>
<head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8;"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <meta name="robots" content="all" />
  <meta name="robots" content="index,follow"/>
</head>
<body>

<script type="text/javascript" src="http://www.qq.com/404/search_children.js"
        charset="utf-8" homePageUrl="your site url "
        homePageName="回到我的主页">
</script>

</body>
</html>

侧边栏社交链接

进入主题配置文件,找到 Social Links 字段。

# Social Links.
# Usage: `Key: permalink || icon`
# Key is the link label showing to end users.
# Value before `||` delimeter is the target permalink.
# Value after `||` delimeter is the name of FontAwesome icon. If icon (with or without delimeter) is not specified, globe icon will be loaded.
social: # 添加你的社交账号
  #LinkLabel: Link
  GitHub: https://github.com/huangfangkai || github
  简书: https://www.jianshu.com/u/e5c418741dce
  #E-Mail: mailto:yourname@gmail.com || envelope
  #Google: https://plus.google.com/yourname || google
  #Twitter: https://twitter.com/yourname || twitter
  #FB Page: https://www.facebook.com/yourname || facebook
  #VK Group: https://vk.com/yourname || vk
  #StackOverflow: https://stackoverflow.com/yourname || stack-overflow
  #YouTube: https://youtube.com/yourname || youtube
  #Instagram: https://instagram.com/yourname || instagram
  #Skype: skype:yourname?call|chat || skype

Next主题美化

文章中添加居中模块

在写文章时添加如下:

    <blockquote class="blockquote-center">以梦为马
    </blockquote>
hexo_blog_Next4

在文章底部增加版权信息

1.在目录 next/layout/_macro/ 下添加 my-copyright.swig,写入如下:

{% if page.copyright %}
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  <!-- JS库 sweetalert 可修改路径 -->
  <script type="text/javascript" src="http://jslibs.wuxubj.cn/sweetalert_mini/jquery-1.7.1.min.js"></script>
  <script src="http://jslibs.wuxubj.cn/sweetalert_mini/sweetalert.min.js"></script>
  <link rel="stylesheet" type="text/css" href="http://jslibs.wuxubj.cn/sweetalert_mini/sweetalert.mini.css">
  <p><span>本文标题:</span><a href="{{ url_for(page.path) }}">{{ page.title }}</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 {{ theme.author }} 的个人博客">{{ theme.author }}</a></p>
  <p><span>发布时间:</span>{{ page.date.format("YYYY年MM月DD日 - HH:MM") }}</p>
  <p><span>最后更新:</span>{{ page.updated.format("YYYY年MM月DD日 - HH:MM") }}</p>
  <p><span>原始链接:</span><a href="{{ url_for(page.path) }}" title="{{ page.title }}">{{ page.permalink }}</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="{{ page.permalink }}"  aria-label="复制成功!"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    clipboard.on('success', $(function(){
      $(".fa-clipboard").click(function(){
        swal({   
          title: "",   
          text: '复制成功',   
          html: false,
          timer: 500,   
          showConfirmButton: false
        });
      });
    }));  
</script>
{% endif %}

2.在目录next/source/css/_common/components/post/下添加my-post-copyright.styl,写入如下:

.my_post_copyright {
  width: 85%;
  max-width: 45em;
  margin: 2.8em auto 0;
  padding: 0.5em 1.0em;
  border: 1px solid #d3d3d3;
  font-size: 0.93rem;
  line-height: 1.6em;
  word-break: break-all;
  background: rgba(255,255,255,0.4);
}
.my_post_copyright p{margin:0;}
.my_post_copyright span {
  display: inline-block;
  width: 5.2em;
  color: #b5b5b5;
  font-weight: bold;
}
.my_post_copyright .raw {
  margin-left: 1em;
  width: 5em;
}
.my_post_copyright a {
  color: #808080;
  border-bottom:0;
}
.my_post_copyright a:hover {
  color: #a3d2a3;
  text-decoration: underline;
}
.my_post_copyright:hover .fa-clipboard {
  color: #000;
}
.my_post_copyright .post-url:hover {
  font-weight: normal;
}
.my_post_copyright .copy-path {
  margin-left: 1em;
  width: 1em;
  +mobile(){display:none;}
}
.my_post_copyright .copy-path:hover {
  color: #808080;
  cursor: pointer;
}

3.修改next/layout/_macro/post.swig,在代码

  {% if theme.wechat_subscriber.enabled and not is_index %}
      <div>
        {% include 'wechat-subscriber.swig' %}
      </div>
  {% endif %}

之前添加增加如下代码:

<div>
     {% if not is_index %}
     {% include 'my-copyright.swig' %}
     {% endif %}
 </div>

4.修改next/source/css/_common/components/post/post.styl文件,在最后一行增加代码:

@import "my-post-copyright"

5.如果要在该博文下面增加版权信息的显示,需要在 Markdown 中增加copyright: true的设置,类似:

---
title: 
date: 
tags: 
categories: 
copyright: true
---

注意:为了方便不用每次添加copyright: true,可以在scaffolds/post.md中设置

title: {{ title }}
date: {{ date }}
tags:
categories: 
notshow: false
copyright: true

---

隐藏网页底部powered By Hexo / 强力驱动

打开themes/next/layout/_partials/footer.swig,使用””隐藏之间的代码即可,或者直接删除。

<!--
<div class="powered-by">
  {{ __('footer.powered', '<a class="theme-link" rel="external nofollow" href="https://hexo.io">Hexo</a>') }}
</div>
<div class="theme-info">
  {{ __('footer.theme') }} -
  <a class="theme-link" rel="external nofollow" href="https://github.com/iissnan/hexo-theme-next">
    NexT.{{ theme.scheme }}
  </a>
</div>
-->

文章加密访问

打开themes->next->layout->_partials->head.swig文件,在meta标签后面插入这样一段代码:

<script>
    (function(){
        if('{{ page.password }}'){
            if (prompt('请输入文章密码') !== '{{ page.password }}'){
                alert('密码错误!');
                history.back();
            }
        }
    })();
</script>

然后文章中添加:

password: nmask

博文置顶

修改 hero-generator-index 插件,把文件:node_modules/hexo-generator-index/lib/generator.js 内的代码替换为:

'use strict';
var pagination = require('hexo-pagination');
module.exports = function(locals){
  var config = this.config;
  var posts = locals.posts;
    posts.data = posts.data.sort(function(a, b) {
        if(a.top && b.top) { // 两篇文章top都有定义
            if(a.top == b.top) return b.date - a.date; // 若top值一样则按照文章日期降序排
            else return b.top - a.top; // 否则按照top值降序排
        }
        else if(a.top && !b.top) { // 以下是只有一篇文章top有定义,那么将有top的排在前面(这里用异或操作居然不行233)
            return -1;
        }
        else if(!a.top && b.top) {
            return 1;
        }
        else return b.date - a.date; // 都没定义按照文章日期降序排
    });
  var paginationDir = config.pagination_dir || 'page';
  return pagination('', posts, {
    perPage: config.index_generator.per_page,
    layout: ['index', 'archive'],
    format: paginationDir + '/%d/',
    data: {
      __index: true
    }
  });
};

在文章中添加 top 值,数值越大文章越靠前,如:

---
......
copyright: true
top: 100
---

修改文章底部的那个带#号的标签

修改模板/themes/next/layout/_macro/post.swig,搜索 rel="tag">#,将 # 换成<i class="fa fa-tag">

Next主题美化

hexo搭建个人博客--NexT主题优化

Hexo搭建博客教程

Hexo博客搭建全攻略(二):NexT主题配置

SEO优化

seo优化对于网站是否能被搜索引擎快速收录有很大帮助,因此适当做一些seo还是有必要的,以下内容参考:

1.添加sitemap文件
安装以下2个插件,然后重启hexo后,网站根目录(source)下会生成sitemap.xml与baidusitemap.xml文件,搜索引擎在爬取时会参照文件中的url去收录。

npm install hexo-generator-sitemap --save-dev
hexo d -g
npm install hexo-generator-baidu-sitemap --save-dev
hexo d -g

2.添加robots.txt
新建robots.txt文件,添加以下文件内容,把robots.txt放在hexo站点的source文件下。

User-agent: * Allow: /
Allow: /archives/
Disallow: /vendors/
Disallow: /js/
Disallow: /css/
Disallow: /fonts/
Disallow: /vendors/
Disallow: /fancybox/
Sitemap: http://thief.one/sitemap.xml
Sitemap: http://thief.one/baidusitemap.xml

Hexo NexT 主题SEO优化指南

相关文章

网友评论

      本文标题:HEXO+Github+Next搭建博客

      本文链接:https://www.haomeiwen.com/subject/ajbniqtx.html