AngularJS HTML5 Mode - How do direct links work without server specific changes? AngularJS HTML5 Mode - How do direct links work without server specific changes? angularjs angularjs

AngularJS HTML5 Mode - How do direct links work without server specific changes?


The AngularJS documentation does in fact mention this

Server side Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)

In this case, one Java-based solution is to tell the server "map all urls to index.html." This can be done in any HTTP Server or container. I implemented this using Java/Servet since I want my application to be HTTP server agnostic (ie Apache versus NginX, or Tomcat/JBoss only).

In web.xml:

  <welcome-file-list>        <welcome-file>index.jsp</welcome-file>  </welcome-file-list>  <servlet>      <servlet-name>StaticServlet</servlet-name>      <jsp-file>/index.jsp</jsp-file>  </servlet>  <servlet-mapping>      <servlet-name>StaticServlet</servlet-name>      <url-pattern>/app</url-pattern>  </servlet-mapping>

And index.jsp simply looks like:

<%@ include file="index.html" %>

And add the following to the tag within index.html:

<base href="/app" />


I spent some time thinking about this for my PHP site. I hang all my server side code off the /api route to keep it separate from Angular. Here is the solution I came up with by updating my apache config:

RewriteEngine on#let the php framework do its thingRewriteRule ^(api/.*)$ index.php?url=$1 [QSA,L,NC]#let angular do its thingRewriteCond %{REQUEST_FILENAME} !-f      RewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*) index.html [NC,L]

I wrote up how I went about this using the Flight PHP framework at http://www.awnage.com/2013/10/10/taking-flight-with-angularjs/


The URLs that you link to, and place in the user's address bar, should refer to valid content on the server, and if at all possible, they should refer to the correct content. Sure, you can just serve the same page for every URL, and have the client code go off and load the real content, and things function pretty much the way they do in the hash-URL world. In fact, that's the least-code way to go. But it also qualifies as "breaking the internet", which is why HTML5 and History API give you a way to link to semantically correct URLs.

As a small example, If you go to https://github.com/kriskowal/q and you click on "examples", the client-side code will load the "examples" direcory into the file browser without leaving the page, and the URL bar will read https://github.com/kriskowal/q/tree/master/examples. If you go to https://github.com/kriskowal/q/tree/master/examples directly, you get the content of the "examples" directory sent directly to your browser, without client-side code intermediating. Yes, this is harder to do, and maybe impossible in a "single page app", but it's the right thing to do any time it's possible.