12

So I've set up an HTML5 single page application, and it's working well. The page is at /App/ and when some one goes to content it looks like /App/Content/1234.

One problem: If the user refreshes the page the server can't find that URL because it doesn't actually exist. If I send them to /App/#/Content/1234, they're golden, but what is the best way to do this? I have a LOT of different styles of URL under /App.

What is the best way to globally catch any request under ~/App/(.*) and redirect it to ~/App/#/$1?

The only route registered in MVC is the standard OOTB route.

Graham
  • 7,431
  • 18
  • 59
  • 84
Ben Lesh
  • 107,825
  • 47
  • 247
  • 232

2 Answers2

4

Sounds like your server is not re-writing the urls to the app's base URL.

The URL re-writing needed on the web server is server-dependent. For Apache, you'd use mod_rewrite.

Instead, switch Angular to the "Hashbang mode" (the default) so the urls will all store the local state after the # in the url.

I don't want my apps to require server configuration changes, so I recommend hashbang mode.

See AngularJS docs. See section "Hashbang and HTML5 Modes" The HTML5 mode section describes all the configuration issues needed to support HTML5 mode for the urls.

Larry K
  • 47,808
  • 15
  • 87
  • 140
  • Yeah, I ended up going back to hashbang mode. Which isn't what I wanted, really, but it will have to do until I come up with a better solution. I'm not on Apache unfortunately, the requirement was Microsoft Technologies (yes that can be a requirement) so until I figure out a good way to do this in ASP.Net, hashbangs it will stay. – Ben Lesh Aug 03 '12 at 14:18
  • 1
    I hear you...the html5 style would sure be nice single page apps but it just aint here yet. Good news is that users don't focus on the url at all--that's why mobile browsers don't even display it once you get into a page. Desktop browsers will be de-emphasizing it in the future too. – Larry K Aug 03 '12 at 14:52
  • The issue I have with using the 'hashbang' method, is that you have to commit to it fully: any link you have that should not refresh the page has to start with a hash and the selected hashPrefix. OTH, in html5 mode, Angular will rewrite the link if it detects a legacy browser. – Schmuli Sep 09 '12 at 21:26
2

This awesome dude describes how to fix this here.

In brief:

  1. Remove MVC nugets (unless you use MVC controllers for anything) - you can keep the Web API nugets. Keep WebPages and Razor packages. Also delete MVC controllers and views.
  2. You can keep using .cshtml files with some web.config modifications. You'll need this for bundling.
  3. Finally you add a rewrite rule on web.config to point all urls (excluding content, images, scripts etc) to index.html
georgiosd
  • 3,038
  • 3
  • 39
  • 51