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

 

Comments

  1. 3rd April 2014 Royce said
    Thanks for this. It was the one that finally worked for me (after trying several from other sites).
    
    I enhanced mine because my app doesn't live off the webserver root. So mine looks like this:
    RewriteEngine On
    RewriteBase /dev/myapp/
    
    # 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 ^(.+)$ /dev/myapp/index.html
    
    Plus I had to add:
    <base href="/dev/myapp/">
    
    to the header of my index.html - now it's all working beautifully and my URLs are free of ugly hashes. :)
  2. 9th March 2016 P K Giriswamy said
    Thanks you  solved my probelm 

Add Comment

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