10th March, 2013

Redirecting into AngularJS for friendly URLs

If you've enabled the HTML5 history API functionality in AngularJS using

$locationProvider.html5Mode(true)

you will probably notice that when you refresh the page in a browser, you get a 404. This is because you've lost the # bookmark, so the browser is requesting a page on your server which doesn't exist.

To fix this in Apache, create a .htaccess file in the root of your AngularJS app and paste the following in:

# If the request is a file, folder or symlink that exists, serve it up
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+)$ - [S=1]

# otherwise, serve your index.html app
RewriteRule ^(.+)$ /index.html

 

The opinions expressed here are my own and not those of my employer.