配置发布单页面静态站点
目前主流的前端框架 React、Vue 都是单页面的:访问所有资源路径时,页面内容其实只有一个(一般是 index.html),其中的 js 框架再根据当前 URL 路由到相应的子页面组件进行渲染。
因此直接访问某个页面资源(例如 /usr/info),这个资源并不存在,服务端就会返回 404。
1 解决方案
编辑配置文件 config/fast-https.json,在 location 中加入 try 模块:
{
"log_root": "./logs",
"pid": "./fast-https.pid",
"http": {
"server": [
{
"listen": 8080,
"server_name": "localhost",
"location": [
{
"url": "/",
"type": "local",
"root": "./httpdoc/club.quwancode.com",
"try": [
{
"uri": "^.*$",
"file": ["index.html", "index.htm"],
"next": "index.html"
}
]
}
]
}
],
"include": [
"./config/conf.d"
]
}
}
Fast-Https 支持 try 模块:当请求路由匹配不到规则、或找不到对应页面资源时,返回 next 指定的资源。
2 配置解析
try 是一个数组,按顺序尝试,每一项包含三个字段:
{
"try": [
{
"uri": "^.*$",
"file": ["index.html"],
"next": ""
},
{
"uri": "^.*$",
"file": ["index.htm"],
"next": "404.html"
}
]
}
| 字段 | 说明 |
|---|---|
uri | 匹配请求路径的正则表达式。不匹配且 next 为空时继续匹配下一项;不匹配且 next 不为空时返回 next |
file | 命中 uri 规则时,默认页面从 file 中依次查找 |
next | 不为空时,找不到页面资源就返回 next 指定的资源 |
单页应用就是把所有未命中的路径统一回退到
index.html;如果你的应用使用 Hash 路由(#/about),不配置 try 也能正常访问。3 验证
保存配置后 RELOAD,先访问根路径,再手动刷新 /user/info 这类子路由,应能正常加载页面而不是 404。