# H5 History模式服务器路由回退配置指南 ## 配置原理 当使用H5的`history`路由模式时,所有直接访问的URL(如刷新页面)都会发送到服务器。服务器需要配置路由回退,将所有匹配不到实际文件的请求重定向到应用的`index.html`,让客户端路由处理URL。 ## 服务器配置示例 ### 1. Nginx配置 ```nginx server { listen 80; server_name yourdomain.com; root /path/to/your/h5/dist; index index.html; # 静态文件直接返回 location ~* \.(jpg|jpeg|png|gif|ico|css|js|ttf|woff|woff2)$ { expires 7d; add_header Cache-Control "public, no-transform"; } # 所有其他请求重定向到index.html location / { try_files $uri $uri/ /hwappx/test/index.html; } } ``` ### 2. Apache配置 需要确保启用了`mod_rewrite`模块 #### .htaccess文件配置 ```apache RewriteEngine On RewriteBase /hwappx/test/ RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /hwappx/test/index.html [L] ``` #### 虚拟主机配置 ```apache ServerName yourdomain.com DocumentRoot /path/to/your/h5/dist AllowOverride All Require all granted RewriteEngine On RewriteBase /hwappx/test/ RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /hwappx/test/index.html [L] ``` ### 3. Express.js配置 ```javascript const express = require('express'); const path = require('path'); const app = express(); // 静态文件服务 app.use('/hwappx/test/', express.static(path.join(__dirname, 'dist'))); // 路由回退 app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'dist', 'index.html')); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` ### 4. IIS配置 需要安装URL重写模块(URL Rewrite Module) #### web.config文件配置 ```xml ``` ## 配置要点 1. **base路径设置**:确保服务器配置中的路径与`manifest.json`中的`base`配置一致 ```json "h5": { "router": { "mode": "history", "base": "/hwappx/test/" } } ``` 2. **静态资源处理**:确保图片、CSS、JS等静态文件能够被正确访问 3. **缓存策略**:为静态文件设置合理的缓存过期时间 ## 验证配置 1. 部署配置后的应用到服务器 2. 访问应用首页 3. 导航到子页面(如`/hwappx/test/pages_tool/form/formdata?id=73&uniacid=2793`) 4. 刷新页面,验证页面是否正常显示 ## 注意事项 - 配置完成后需要重启服务器生效 - 确保服务器有权限读取配置文件 - 对于HTTPS站点,需要在对应的HTTPS配置中添加相同的路由回退规则 - 如果使用CDN,需要确保CDN也配置了相应的路由回退规则