伪静态路由设计
RyeBlog 使用 /:slug 而非 /article/:slug。URL 更短、更优雅,但背后有重要的工程考量。
为什么用伪静态路由?
用户体验
ryeblog.com/my-first-post— 干净、简洁、好记ryeblog.com/article/my-first-post— 冗余、啰嗦
SEO
搜索引擎更喜欢短 URL。Google 官方文档建议:"URL 应该尽量简短,只包含必要的路径段。"
分享
在社交媒体、邮件、聊天中粘贴短 URL,更不容易被截断,视觉上也更清爽。
实现方式
Cloudflare Pages Functions 使用文件系统路由:
functions/
index.js → /
[slug].js → /:slug
category/
[id].js → /category/:id
tag/
[name].js → /tag/:name
archive.js → /archive
tags.js → /tags
search.js → /search
about.js → /about
rss.xml.js → /rss.xml
sitemap.xml.js → /sitemap.xml
[slug].js 是动态路由,会拦截所有 /:slug 请求。在函数内部,我们查询数据库判断 slug 对应的是文章、分类还是其他类型。
静态资源拦截问题
伪静态路由有一个陷阱:[slug].js 会拦截所有 /:slug 请求,包括 /style.css、/favicon.ico 等静态资源。
问题复现
当浏览器请求 /style.css 时:
- Pages Functions 路由匹配
[slug].js,slug =style.css - 函数查询数据库,找不到 slug 为
style.css的文章 - 返回 404,CSS 加载失败
- 页面样式全部丢失
解决方案
在 [slug].js 中排除带文件扩展名的路径:
export async function onRequestGet(context) {
const { params } = context;
const slug = params.slug;
// 排除静态资源(带扩展名的路径)
if (slug.includes('.')) {
return context.next();
}
// 正常的文章查询逻辑
const article = await context.env.DB.prepare(
'SELECT * FROM articles WHERE slug = ? AND status = ?'
).bind(slug, 'published').first();
if (!article) {
return new Response('Not Found', { status: 404 });
}
const html = renderArticlePage(article, context.env);
return new Response(html, {
headers: { 'Content-Type': 'text/html; charset=utf-8' }
});
}
context.next() 将请求传递给下一个处理器(即 Pages 的静态资源服务),让 Cloudflare 正常返回 CSS、JS、图片等静态文件。
CDN 缓存陷阱
另一个陷阱:Cloudflare CDN 会缓存响应。如果你部署了错误的 CSS,即使修复后重新部署,CDN 可能仍然返回旧的缓存版本。
解决方案
在 HTML 中引用 CSS 时加版本号查询参数:
<link rel="stylesheet" href="/style.css?v=2">
每次更新 CSS 后递增版本号,浏览器和 CDN 都会视为新资源,不会返回缓存。
路由优先级
Pages Functions 的路由匹配有优先级:
- 精确匹配优先:
/archive会优先匹配archive.js,而非[slug].js - 静态资源优先:
/style.css如果在public/目录或项目根目录存在,会优先作为静态资源返回 - 动态路由最后:
[slug].js是最后的兜底路由
这就是为什么我们需要在 [slug].js 中手动排除带扩展名的路径——因为某些情况下静态资源匹配可能不生效(取决于 pages_build_output_dir 配置)。',