You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

124 lines
3.4 KiB
Markdown

4 months ago
# 前端路由刷新404问题解决方案
## 问题描述
使用 Vue Router 的 `history` 模式时,当用户直接访问或刷新非根路径的页面时(如 `http://xiyan.cxmom.com/board/kanban`),服务器会返回 404 错误。
这是因为浏览器会向服务器请求该路径,但服务器上并没有这个实际的文件或目录。
## 解决方案
根据你使用的 Web 服务器,选择相应的配置:
### 1. Nginx 配置
`nginx.conf` 文件中的配置添加到你的 Nginx 配置中。
**关键配置**
```nginx
location / {
try_files $uri $uri/ /index.html;
}
```
这个配置的含义是:
- 首先尝试找到请求的文件(`$uri`
- 如果不存在,尝试找到对应的目录(`$uri/`
- 如果都不存在,返回 `index.html`,由 Vue Router 处理路由
**完整配置示例**见 `nginx.conf` 文件。
### 2. Apache 配置
`.htaccess` 文件复制到你的 `dist` 目录根目录下。
**关键配置**
```apache
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
```
确保 Apache 启用了 `mod_rewrite` 模块。
### 3. 其他服务器
#### Node.js (Express)
```javascript
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'dist')));
// Vue Router history 模式 fallback
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
```
#### Node.js (Koa)
```javascript
const Koa = require('koa');
const serve = require('koa-static');
const { historyApiFallback } = require('koa2-connect-history-api-fallback');
const app = new Koa();
app.use(historyApiFallback());
app.use(serve('dist'));
```
#### IIS (web.config)
创建 `web.config` 文件:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Handle History Mode and hash fallback" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
```
### 4. Spring Boot如果前端文件集成在后端
如果前端文件已经复制到 `src/main/resources/static/` 目录,后端已经配置了 `FrontendController``ResourcesConfig`,应该可以正常工作。
## 部署步骤
1. **构建前端项目**
```bash
cd xiyan-ui
npm run build:prod
```
2. **根据你的服务器类型**
- **Nginx**:将 `dist` 目录内容复制到服务器,并配置 `nginx.conf`
- **Apache**:将 `dist` 目录内容和 `.htaccess` 文件复制到服务器
- **其他服务器**:使用相应的配置
3. **重启服务器**使配置生效
## 验证
配置完成后,测试以下场景:
1. ✅ 直接访问 `http://xiyan.cxmom.com/` - 应该正常显示首页
2. ✅ 访问 `http://xiyan.cxmom.com/board/kanban` - 应该正常显示看板页面
3. ✅ 在 `http://xiyan.cxmom.com/board/kanban` 页面刷新浏览器 - **不应该**再出现 404
## 注意事项
1. 确保静态资源路径正确(`/static/**`
2. 确保 API 代理配置正确(如果前端独立部署)
3. 配置后记得重启 Web 服务器