要支持前端 Vue/React 等框架的 History 模式(URL 无 #),核心是解决刷新页面时服务器 404 的问题:当浏览器请求不存在的路径时,服务器需返回 index.html,让前端路由接管。
以下是 Nginx、Koa2、Express 的具体配置方案:
一、Nginx 配置(推荐用于生产环境)
Nginx 作为反向代理服务器,通过 try_files 指令实现回退到 index.html。
配置示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| server { listen 80; server_name your-domain.com;
root /path/to/your/dist; index index.html;
location / { try_files $uri $uri/ /index.html; }
location /api/ { proxy_pass http://127.0.0.1:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }
|
关键点说明
try_files $uri $uri/ /index.html:优先访问真实文件/目录,不存在则返回 index.html。
- API 路径(如
/api/)需单独配置 proxy_pass,否则会被误判为前端路由。
二、Koa2 配置
使用 koa-connect-history-api-fallback 中间件实现 History 模式支持。
1. 安装依赖
1
| npm install koa-connect-history-api-fallback koa-static
|
2. 完整代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| const Koa = require('koa'); const serve = require('koa-static'); const history = require('koa-connect-history-api-fallback'); const path = require('path');
const app = new Koa();
app.use(history({ rewrites: [ { from: /^\/api/, to: '/api' } ] }));
app.use(serve(path.join(__dirname, 'dist')));
app.use(async (ctx) => { if (ctx.path.startsWith('/api')) { ctx.body = { message: '这是后端 API 响应' }; } });
app.listen(3000, () => { console.log('Koa2 服务器运行在 http://localhost:3000'); });
|
关键点说明
history() 中间件必须放在 serve() 之前,确保先处理路由回退。
- 通过
rewrites 排除 API 路径,避免后端接口被拦截。
三、Express 配置
使用 connect-history-api-fallback 中间件(与 Koa2 原理类似)。
1. 安装依赖
1
| npm install connect-history-api-fallback express
|
2. 完整代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| const express = require('express'); const history = require('connect-history-api-fallback'); const path = require('path');
const app = express();
app.use(history({ rewrites: [ { from: /^\/api/, to: '/api' } ] }));
app.use(express.static(path.join(__dirname, 'dist')));
app.get('/api/hello', (req, res) => { res.json({ message: '这是后端 API 响应' }); });
app.listen(3000, () => { console.log('Express 服务器运行在 http://localhost:3000'); });
|
关键点说明
- 中间件顺序:
history() → express.static() → API 路由。
- 若 API 路径与前端路由冲突,需通过
rewrites 明确排除。
四、通用注意事项
API 路径隔离:
- 建议后端 API 统一加前缀(如
/api),避免与前端路由路径冲突。
- Nginx/Koa/Express 配置中需确保 API 请求不被回退到
index.html。
静态资源路径:
- 前端构建后的
dist 目录需正确配置到服务器的静态资源路径。
- 确保
index.html 中的资源引用(如 js/css)使用相对路径或正确的绝对路径。
多级路由嵌套:
- 若前端有嵌套路由(如
/user/profile/123),上述配置仍有效(因 try_files 或中间件会统一回退到 index.html)。
生产环境推荐:
- 用 Nginx 托管前端静态文件 + 反向代理后端 API(性能更好,配置更灵活)。