Monday, 5 June 2017

AngularJS: Page refresh problem after removing # from URL


AngularJS has a lot of services that makes several tasks easier. One of them is AngularJS Routing Service. AngularJS Routing Service allows developers to build quick & faster applications by using Ajax techniques to load partial pages without page reload. This service usually puts a # in  URL which makes the URL Non SEO-Friendly. like below:

http://localhost/angularJS/#/courses

 In our previous article, We have discussed How to remove # from URL but this is not enough, Because removing the # from URL will create a new problem for you which is page refresh problem.Actually, When a route is changed, the browser can't recognize the URL generated by AngularJS if it has no #. So as a result, it shows page not found error.

Take a look at bleow screenshot (with #):


If we remove # by converting html5Mode to true (# also removed from links), it shows page normally without # in address bar.But when we reload the page, it show 404 error:



To get rid of  this issue, we have to create an file in the root directory with .htaccess name to rewrite urls:

RewriteEngine on

# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]

It's also neccessary to specify the base url.


We've solved the issue.

Always be happy

0 comments:

Post a Comment