uniapp打包h5直接访问/pages的路径导致404怎么解决
uniapp打包成H5后,直接访问/pages路径下的页面会出现404错误,该怎么解决?比如配置了路由但访问/pages/index/index时无法正常加载,需要如何调整配置或服务器设置?
2 回复
在manifest.json的h5配置中添加router的mode为'hash',避免路径问题。或者配置服务器将所有路径重定向到index.html。
在UniApp中,直接访问H5打包后的 /pages 路径(如 example.com/pages/index/index)出现404错误,是因为UniApp默认使用前端路由模式(history模式),但服务器未配置相应的路由重定向规则。以下是解决方法:
1. 配置服务器路由重定向
将服务器设置为所有未匹配的静态资源请求都指向 index.html,由前端路由处理。以常见服务器为例:
-
Nginx: 在配置文件中添加:
location / { try_files $uri $uri/ /index.html; } -
Apache: 在项目根目录创建
.htaccess文件,内容为:RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] -
Tomcat: 在
web.xml中添加:<error-page> <error-code>404</error-code> <location>/index.html</location> </error-page>
2. 修改UniApp路由模式为hash模式
如果无法配置服务器,可在 manifest.json 中改用hash模式(URL中带 #):
{
"h5": {
"router": {
"mode": "hash"
}
}
}
修改后,URL会变为 example.com/#/pages/index/index,可避免服务器配置问题。
3. 检查静态资源路径
在 manifest.json 中确认 h5.publicPath 设置正确(通常为 ./):
{
"h5": {
"publicPath": "./"
}
}
总结
- 优先配置服务器重定向(推荐),确保所有路径指向
index.html。 - 无法配置服务器时,改用 hash 模式。
- 部署前测试本地构建,确保资源加载正常。
根据实际环境选择方案即可解决问题。

