AngularJS开启HTML5 Mode后哈希模式未移除,路由切换失效问题
AngularJS ngRoute HTML5模式路由问题解决
问题核心
开启HTML5模式后,点击路由链接出现#%2Fabout编码URL且内容不更新,刷新非根路由返回404。
解决步骤
1. 修正导航链接格式
开启HTML5模式后,需放弃带#的哈希式链接,改用标准路径,推荐使用AngularJS的ng-href指令确保路由正确解析:
<nav> <a ng-href="/">Home</a> <a ng-href="/about">About</a> <a ng-href="/contact">Contact</a> </nav>
若不想使用ng-href,直接修改href为/about也可,但ng-href能避免页面初始化前的链接跳转异常。
2. 完善$locationProvider配置
AngularJS 1.6+版本默认哈希前缀为!,即使开启HTML5模式,该设置仍会干扰路由解析,需取消hashPrefix的注释并设置为空:
app.config(function ($routeProvider, $locationProvider) { $routeProvider .when("/", { templateUrl: "templates/home.html", }) .when("/about", { templateUrl: "templates/about.html", }) .when("/contact", { templateUrl: "templates/contact.html", }) .otherwise({ redirectTo: "/" }); $locationProvider.hashPrefix(''); // 启用这行配置 $locationProvider.html5Mode(true); });
此操作可消除URL中的#%2F编码问题,让Angular正确处理HTML5模式下的路径跳转。
3. 服务器端配置路由重写
刷新非根路由出现404,是因为服务器会尝试查找对应文件/目录,而SPA所有路由都需指向index.html,根据你的服务器类型配置:
- 本地调试用http-server:启动时添加重写参数:
http-server -p 8000 -P http://localhost:8000? - Nginx:在server块中添加规则:
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]
内容的提问来源于stack exchange,提问作者Kushal
相关产品推荐
相关产品推荐

