Nginx and Angularjs routes

Angularjs is quickly gaining traction as a javascript framework. One noticeable problem is the ugly (read: not SEO or human friendly) urls exposed through its routing mechanism. For example, a typical url ends up looking like /index.html#/foo. A “prettier” way to expose this would be as simple /foo. Nginx is a very popular web server and while there are a million examples of simple http 301 redirects and handling php files, there weren’t great examples for this simple scenario. So, here it is in all its glory, tested on nginx 1.2.6:

Add a block like the following to nginx.conf:

location =/foo {
rewrite ^ /index.html#/foo permanent;

One downside is that you’ll likely need a block like this for each url you want mapped. In theory one could write a regular expression that would take the uri and append it to the end of the rewrite, but in practice I couldn’t get it to work. If the information on the web is to be believed, it is slightly better performance to do an explicit match (in this case to exactly “/foo”) than to do the regex comparison.