AngularJS pretty URL – Remove #(Hash)

6
458

Why we should remove # from URL?

It will affect in SEO as google ignore everything after #(hash) in the URL.So suppose our url is www.example.com/#/products so when user visit this url only www.example.com/ will be logged as a visited url.Everything after # will be removed.

Two step to make url pretty(Remove #)

  • Client Side (Angular JS)
  • Server Side (NodeJS)(Kind Of Url Rewrite)

Github Code Example

If you don’t want to go into detail and directly want to see code then here is the Github Repo.
Below is the detail explanation of that example.

Client Side Code Change

By default AngularJS add hashtag to application url.
To remove # from url we will use AngularJS’s $locationProvider’s method named html5Mode().
In this example I am using
Angular UI Router for routing purpose
Webpack for modular builds.
oclazyload for module lazy loading.

Step 1 : Changes in app.js link

app.config(['$stateProvider', '$urlRouterProvider','$locationProvider',function($stateProvider, $urlRouterProvider,$locationProvider){
	$stateProvider
		.state('screen1',{
			url : '/screen1',
			...
		})
		.state('screen2',{
			url : '/screen2',
			....
		});
	$urlRouterProvider.otherwise('/screen1');
	//Client side Configuration to pretty url
	//Remove # from url
	$locationProvider.html5Mode(true);
}])

Hightlighted line $locationProvider.html5Mode(true); is responsible to remove # from url.
Add this line in your app.config function also don’t forget to inject $locationProvider in app.config.
That’s not it.
If you run your application now, you will get error $location in HTML5 mode requires a <base> tag to be present!.That says you have to add ‘base’ tag in your index.html file.

The HTML <base> element specifies the base URL to use for all relative URLs contained within a document. There can be only one element in a document. Reference

Step 2 : Add <base> in index.html link
<!doctype html>
        
        
        
        
        
    
    
        



See highlighted line and add that line to your index.html.
Now if you run application if url is localhost/#/screen1 this then it will change to localhost/screen1 this.
So we successfully make url pretty and removed #(hash).
But wait one problem is there, if you directly go to localhost/screen1 then it will try to find /screen1 route in node server and will return not found error and it will not return our required angular page.
So to overcome this problem we have to do some server side changes.

Server Side Code Change

Go to main app.js of your server file where you are registering all routes of your application.In our github example App.js is the main file.
Here we are using express for routing.
We can register middleware for any route using app.use.For more info about middleware.

6 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here