基于 Nginx 建立 Hexo 和 Jupyter 实现在线编辑和科学计算

基于 Nginx ,在服务器同时搭建了 Hexo 和 Jupyter,可以使用 Jupyter 直接在线编辑 Markdown 并发布,同时能够直接看到 Hexo 博客的效果。服务器使用的是 GCP 提供的免费试用服务,域名是 freedom 免费域名,使用 Cloudflare 的 DNS 和 CDN 服务,开启 https 加密。其实就是全部免费啦,可以根据自己的情况换用不同的服务。

环境安装

安装 Anaconda

$ wget https://repo.anaconda.com/archive/Anaconda3-5.3.1-Linux-x86_64.sh
$ bash Anaconda3-5.3.1-Linux-x86_64.sh

安装 Node.js 和 Git

$ sudo apt-get install git-core
$ wget -qO- https://raw.github.com/creationix/nvm/v0.33.11/install.sh | sh
$ nvm install stable

安装 Hexo

$ npm install -g hexo-cli

Hexo 配置

首先执行下面命令建站

$ hexo int hexo
$ cd hexo
$ npm install

然后生成静态文件

$ hexo g

这里介绍了最简单的配置,其他详细信息请到 Hexo 官网查看

配置 Jupyter Notebook

$ jupyter notebook --generate-config

生成配置文件,位置为 ~/.jupyter/jupyter_notebook_config.py

$ jupyter notebook password

设置密码,文件位于 ~/.jupyter/jupyter_notebook_config.json

{
  "NotebookApp": {
    "password": "sha1:123456789:0987654321abcdefghijklmno"
  }
}

将 psaaword 部分复制到配置文件中,可以参考

#c.NotebookApp.base_url = '/jupyter'
c.NotebookApp.password = 'sha1:123456789:0987654321abcdefghijklmno'
c.NotebookApp.ip = 'localhost'
c.NotebookApp.port = 6789
c.NotebookApp.port_retries = 50
c.NotebookApp.allow_origin = '*'
c.NotebookApp.contents_manager_class = 'notedown.NotedownContentsManager'
c.NotebookApp.open_browser = False

然后使用 nohup 后台运行

$ nohup jupyter notebook &

配置 Nginx

首先安装 Nginx

$ sudo apt-get install nginx

然后编辑 Nginx 配置文件,默认位于 /etc/nginx/site-enabled/default,可以参考下面配置,SSL 证书可以直接下载 Cloudflare 提供的免费证书,或者使用 Let’s encrypt 等申请。

server {
  listen 80 jupyter;
  listen [::]:80 jupyter;
  listen 443 ssl jupyter;
  listen [::]:443 ssl jupyter;
  ssl on;
  ssl_certificate /etc/ssl/private/private.pem;
  ssl_certificate_key /etc/ssl//private/private.key;

  access_log     /var/log/nginx/jupyter.access.log;
  error_log      /var/log/nginx/jupyter.error.log;

  root /var/www/root;
  server_name jupyter.domain.example;
  index index.html index.htm index.nginx-debian.html;

  location / {
    proxy_pass http://127.0.0.1:6789;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $http_host;
    proxy_http_version 1.1;
    proxy_redirect off;
    proxy_buffering off;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_read_timeout 86400;
  }
}

server {
  listen 80 hexo;
  listen [::]:80 hexo;
  listen 443 ssl hexo;
  listen [::]:443 ssl hexo;
  ssl on;
  ssl_certificate /etc/ssl/private/private.pem;
  ssl_certificate_key /etc/ssl//private/private.key;

  access_log     /var/log/nginx/hexo.access.log;
  error_log      /var/log/nginx/hexo.error.log;

  root ~/hexo/public;
  server_name jupyter.domain.example;
  index index.html index.htm index.nginx-debian.html;
}

然后重新加载 Nginx

$ sudo systemctl restart nginx

到此应该就可以正常访问 Jupyter 和 Hexo 了,之后可以使用 Jupyter Notebook 编辑文章,使用自带的 Terminal 进行生成静态网页。也可以参考官方将网页发布到 GitHub 并绑定自己域名访问。