AngularJS:开启HTML5模式后页面刷新无404错误解决方案求助
这问题我之前折腾过好几次,太懂这种刷新就404的崩溃感了!本质是开启html5Mode(true)后,浏览器会把路由当成真实的服务器路径请求,而服务器根本不知道这些前端路由对应的资源,所以直接返回404。解决核心就是让服务器把所有前端路由的请求,都转发到你的入口文件(一般是index.html),交给Angular的ui-router去处理。
当你开启html5Mode后,URL从http://localhost/rootfoldername/#/home变成了http://localhost/rootfoldername/home。正常跳转时是前端路由在处理,但刷新页面时,浏览器会直接向服务器请求/rootfoldername/home这个路径,服务器找不到对应的文件或后端路由,就返回404了。我们要做的就是让服务器“兜底”,把这类请求都指向index.html。
下面是几种常用服务器的具体配置方法,你对应自己的服务器来就行:
Apache服务器
在项目根目录创建.htaccess文件,写入以下内容:
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase /rootfoldername/ RewriteRule ^index\.html$ - [L] # 如果请求的不是文件或目录,就转发到index.html RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /rootfoldername/index.html [L] </IfModule>
注意:要确保Apache已经开启了mod_rewrite模块,不然这个配置不会生效。
Nginx服务器
找到你的Nginx配置文件(一般在/etc/nginx/conf.d/或/etc/nginx/sites-available/目录下),在对应的server块里添加如下配置:
location /rootfoldername/ { # 先尝试访问文件或目录,找不到就返回index.html try_files $uri $uri/ /rootfoldername/index.html; }
配置完记得重启Nginx服务(sudo systemctl restart nginx)让配置生效。
Node.js Express服务器
如果用Express做后端服务,添加一个兜底的路由中间件:
const express = require('express'); const path = require('path'); const app = express(); // 托管静态资源(比如你的前端文件放在public目录下) app.use('/rootfoldername', express.static(path.join(__dirname, 'public'))); // 所有未匹配到的请求,都返回index.html app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); app.listen(3000, () => { console.log('服务器运行在3000端口'); });
这里要注意public路径要和你的实际前端文件目录对应,别写错了。
- 你的
<base href="http://localhost/rootfoldername/">配置是对的,结尾的斜杠一定要保留,不然可能会导致CSS、JS等资源加载路径错误。 - 如果是开发环境用Angular官方的
ng serve,其实它已经默认处理了这个刷新404的问题,不用额外配置;但如果是自己搭的服务器,就必须按上面的方法配置。 - 配置完后一定要重启服务器,不然新配置不会生效哦!
内容的提问来源于stack exchange,提问作者manishkummar

