Tutorial: Hosting hexo subdirectory site on Netlify

Netlify has been trending recently with its offerings of free static site hosting with CI-like continuous deployment and automatic https configuration. However Netlify [does not support deploying site to a subdirectory]. The workaround is to setup rewrite rules.

Background

This blog is generated by hexo has been hosted on cs.mcgill.ca since 2013. While I own the xiamx.me domain, it was mainly set as 301 redirect to cs.mcgill.ca/~mxia3.

Recently, I wanted to make this blog fully available on xiamx.me via netlify, but encountered a issue while trying to deploy the site to netlify. Originally this blog is available under the subdirectory ~mxia3 of cs.mcgill.ca. Historically, when shared web hosting were still popular, each system user on cs.mcgill.ca would be able to host their site inside their $HOME/public_html directory, and their public url will be http://hostname/~username. With containers and modern web deployments, this style is no longer popular.

To support cs.mcgill.ca/~mxia3 style of website root directory, hexo was configured to generate links relative to the root ~mxia3 with the folliwng _config.yml configuration

1
2
3
4
5
6
7
8
# Hexo Configuration
## Docs: https://hexo.io/docs/configuration.html
## Source: https://github.com/hexojs/hexo/

# URL
## If your site is put in a subdirectory, set url as 'http://yoursite.com/child' and root as '/child/'
url: https://cs.mcgill.ca/~mxia3
root: /~mxia3/

However Netlify does not support subdirectory site deployment. And when the site is deployed to the root of https://xiamx.me, many links fail to work. For example https://xiamx.me/~mxia3/2019/02/24/Using-gRPC-in-Production/ because ~mxia3 subdirectory is not present under https://xiamx.me.

Workaround

A workaround to this is to add proxy rules by creating netlify.toml file under the root directory of the project with content like the following:

1
2
3
4
5
[[redirects]]
from = "/~mxia3/*"
to = "/:splat"
status = 200
force = true

This redirect rule turns every /~mxia3/* url into requesting the resource directly in the root direcotry / so that a request to https://xiamx.me/~mxia3/2019/02/24/Using-gRPC-in-Production/ is proxied to https://xiamx.me/2019/02/24/Using-gRPC-in-Production/ behind the scene.