利用Pages托管静态站点

从边栏进入计算(Workers)->Workers和Pages,创建一个Pages应用程序。如果博客代码是托管在github或gitlab中,则选择连接到git,否则直接上传public文件夹中的内容即可。

当前Pages还不支持Hexo,选择好托管的仓库后,在构建设置中按下图填写构建命令和输出目录。

最后,点击保存并部署后,等待cloudflare拉取代码并部署博客即可。部署完成后,cloudflare会自动分配一个url用于访问博客,也可以在自定义域中绑定自己的域名。

308重定向问题

当请求的URL包含html后缀时,Pages会将请求URL重定向到不含html后缀的地址去。

在GitHub上已经有人提出了这个问题,但是对于Pages当前没有配置项来修改这一行为。

🚀 Feature Request: Urgently need a way to disable redirects from foo.html to foo with Pages · Issue #1488 · cloudflare/workers-sdk

本人的解决方法是利用Workers配合Static Assets来托管博客。

配置Workers环境

在hexo博客根目录,运行npm install wrangler --save-dev安装用于管理Workers工程的CLI工具wrangler

新建一个wrangler.toml文件,并写入如下配置:

name = "hexo-site"
main = "cf_src/index.js"
compatibility_date = "2025-01-18"

[assets]
directory = "./public"
binding = "ASSETS"
html_handling = "none"
not_found_handling = "404-page"

[observability]
enabled = true

[placement]
mode = "smart"

name为工程名字,可以自定义。main为workers脚本,根据实际情况填写。

html_handling和not_found_handling根据需求填写,具体可参考文档:https://developers.cloudflare.com/workers/wrangler/configuration/https://developers.cloudflare.com/workers/static-assets/routing/#html_handling

我本身并不希望cloudflare将URL的html后缀取消,所以将html_handling设置为none。并且我有自己的404页面,所以not_found_handling使用404-page

默认配置下(experimental_serve_directly =true),Static Assets仅会将未找到对应文件的请求交由workers脚本处理。而Hexo博客中时常会创建tags/,categories/,archives/等页面,这些URL一般不带html后缀,如果使用上述配置,我们就无法访问这些页面。所以需要一个workers脚本对这些页面进行额外的处理。

编写Workers脚本

export default {
async fetch(request, env) {
const url = new URL(request.url);
if (url.pathname.endsWith("/")) {
const newUrl = request.url + "index.html";
const modifiedRequest = new Request(newUrl, request);
return env.ASSETS.fetch(modifiedRequest);
}
// Passes the incoming request through to the assets binding.
// No asset matched this request, so this will evaluate `not_found_handling` behavior.
return env.ASSETS.fetch(request);
},
};

在配置文件中,我们通过binding = "ASSETS"将文件资源绑定到ASSETS环境变量上,在脚本中就可以使用env.ASSETS直接访问这些文件。上述脚本只是简单地对请求的URL添加index.html后缀,如果有更复杂的需求,可以自行编写脚本。

部署Workers工程

运行wrangler deploy即可将Workers工程部署到cloudflare上。

访问博客页面不再会有重定向。

Github action自动化

使用cloudflare/wrangler-action@v3可以自动部署Workers工程。申请并填入account id和api token即可。

jobs:
build:
steps:
# ... other steps
- name: Deploy to Cloudflare Worker
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}