简体   繁体   English

我应该如何构造AngularJS路由来处理URL重写和页面刷新?

[英]How should I structure my AngularJS routing to handle URL rewriting and page refreshes?

I'm building my own website using AngularJS. 我正在使用AngularJS建立自己的网站。 I want my site's navigation to behave without the "browser flash" that exists when you go between pages, eg clicking a link on index.html that takes you to foo.html . 我希望我的网站导航在没有页面浏览时存在的“浏览器闪烁”的情况下运行,例如,单击index.html上的链接,该链接将您带到foo.html I also want clean URLs, so for instance I can go to mysite.com/foo and have the browser display the content in foo.html . 我还希望使用干净的URL,例如,我可以转到mysite.com/foo并让浏览器在foo.html显示内容。

Angular's client-side routing in HTML5 mode is an effective solution, but there are exceptions: Angular在HTML5模式下的客户端路由是一种有效的解决方案,但也有例外:

If I go to mysite.com , I can configure $routeProvider to map the view to the appropriate partials (eg index.html or foo.html ) and modify the URL the browser displays. 如果转到mysite.com ,则可以配置$routeProvider以将视图映射到适当的部分(例如index.htmlfoo.html ),并修改浏览器显示的URL。 However, if I go to mysite.com/foo by directly typing that URL into the browser, I will get a 404 error because the server is looking for something in mysite.com/foo/ that isn't there. 但是,如果我通过直接在浏览器中键入URL来访问mysite.com/foo ,则会收到404错误,因为服务器正在mysite.com/foo/中查找不存在的内容。 The same will happen if I refresh the page while Angular is pointing to mysite.com/foo . 如果在Angular指向mysite.com/foo时刷新页面,也会发生同样的情况。

In short, navigating to mysite.com/foo is only handled properly if navigated from within the Angular app. 简而言之,仅当从Angular应用程序中导航时,才能正确处理导航到mysite.com/foo

How can I handle this so that my site behaves the way I want? 如何处理此问题,以便我的网站按照我想要的方式运行? Do I use PHP and/or mod_rewrite to redirect the browser back to mysite.com upon 404? 是否在404时使用PHP和/或mod_rewrite将浏览器重定向回mysite.com

In essence, I want the URL mysite.com/foo to display the mysite.com view + the foo.html partial whether the URL is set by Angular or manually typed in the browser URL bar . 本质上, 无论URL是由Angular设置还是在浏览器URL栏中手动键入 ,我都希望URL mysite.com/foo显示mysite.com视图+ foo.html部分。

Yes you need something like mod_rewrite. 是的,您需要类似mod_rewrite的东西。

http://ericduran.io/2013/05/31/angular-html5Mode-with-yeoman/ http://ericduran.io/2013/05/31/angular-html5Mode-with-yeoman/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM