您的位置:首页 > 编程语言 > Lua

angluar去掉url中#

2015-07-09 16:23 113 查看
众所周知,angular项目中路由机制会在地址栏加一个#来实现各个页面的切换,虽然url中有个#号也无伤大雅,但每次看到多一个这个东西总是不舒服(我不是强迫证啊),趁着项目间隙还是决定把它去掉。

去谷哥百度一下,发现用html5的形式也解决这个问题,就一行代码,so easy.

$locationProvider.html5Mode('true');


我把这行代码加入了app.js的config中然后运行一下,发现并没有什么卵用,还报了错。

好吧,原来还要加index.html的header中加入base标签。

<base href="/">


OK, base标签加上之后果然运行成功,#成功去掉。

等等!

然而并没有那么简单,当我刷新页面时居然报出了404,什么鬼?!

在谷歌的帮助下我找到了原因,我还是太天真了,上边这种形式只适用于客户端的页面跳转,不适用于重新请求服务器。。。这不是坑爹吗?

终于还在谷歌的帮助下,还是让我找到了服务器端的解决方案,修改apache的配置文件,利用rewrite对发过来url地址进行重写(要确保apache中已安装rewrite模块)。

apache配置文件:

<VirtualHost *:80>
ServerName my-app

DocumentRoot /path/to/app

<Directory /path/to/app>
RewriteEngine on

# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]
</Directory>
</VirtualHost>


重新启动apache,运行成功,完美去掉#。

打完收工。

参考1 https://github.com/yeoman/generator-angular/issues/433

参考2 https://scotch.io/quick-tips/pretty-urls-in-angularjs-removing-the-hashtag

参考3 http://www.tech.theplayhub.com/angularjs_routeprovider_404/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: