Neat and Clean URL in AnjularJS : Remove the #

Tags

,

Neat and Clean URL in AnjularJS : Remove the #

For example:

  • http:// myapp.com/
  • http:// myapp.com/#/about
  • http:// myapp.com/#/contact

It is very easy to get clean URLs and remove the #  from the URL as.

  • http:// myapp.com/
  • http:// myapp.com/about
  • http:// myapp.com/contact

There are 3 things that need to be done.

  1. Configuring $locationProvider

  2. Setting our base for relative links

  3. Configure your server to work with html5Mode
  1. Configuring $locationProvider

$location Service

In Angular, the $location service parses the URL in the address bar and makes changes to your application and vice versa.

$locationProvider and html5Mode

We will use the $locationProvider module and set html5Mode to true.
We will do this when defining your Angular application and configuring your routes.

angular.module(‘myApp’, [])

.config(function($routeProvider, $locationProvider) {
// use the HTML5 History API
$locationProvider.html5Mode(true);

$routeProvider
.when(‘/’, {
templateUrl : ‘/home.html’,
controller : homeController
})
.when(‘/about’, {
templateUrl : ‘/about.html’,
controller : aboutController
})
.when(‘/contact’, {
templateUrl : ‘/contact.html’,
controller : contact Controller
});

});

HTML5 History API is a standardized way to manipulate the browser history using a script. This lets Angular change the routing and URLs of our pages without refreshing the page.

  1. Setting our base for relative links

Setting For Relative Links

To link around your application using relative links, you will need to set a <base> in the <head> of your document.

<!DOCTYPE html>
<html ng-app=”myApp” lang=”en”>
<head>
<meta charset=”utf-8″>
<base href=”/”>
</head>
<body>
<a href=”/”>Home</a>
<a href=”/about”>About</a>
<a href=”/contact”> Contact </a>

</div>

</body>

There are plenty of other ways to configure this and the HTML5 mode set to true should automatically resolve relative links.
The $location service will automatically fallback to the hashbang method for browsers that do not support the HTML5 History API.

  1. Configure your server to work with html5Mode

When add $locationProvider.html5Mode(true), site will not allow pasting of urls. How do I configure my server to work when html5Mode is true?
When you have html5Mode enabled, the # character will no longer be used in your urls. The # symbol is useful because it requires no server side configuration. Without #, the url looks much nicer, but it also requires server side rewrites. Here are some
Examples:

Apache Rewrites

<VirtualHost *:80>
ServerName my-app
DocumentRoot /path/to/app
<Directory /path/to/app>
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]
</Directory>
</VirtualHost>
Nginx Rewrites
server {
server_name my-app;
root /path/to/app;
location / {
try_files $uri $uri/ /index.html;
}
}

Azure IIS Rewrites

<system.webServer>
<rewrite>
<rules>
<rule name=”Main Rule” stopProcessing=”true”>
<match url=”.*” />

<!–
in  case rest API calling from angularJS and api string in url <match url=^((?!api).)*$ />
–>

<conditions logicalGrouping=”MatchAll”>
<add input=”{REQUEST_FILENAME}” matchType=”IsFile” negate=”true” />
<add input=”{REQUEST_FILENAME}” matchType=”IsDirectory” negate=”true” />
</conditions>
<action type=”Rewrite” url=”/” />
</rule>
</rules>
</rewrite>
</system.webServer>

Express Rewrites

var express = require(‘express’);
var app = express();
app.use(‘/js’, express.static(__dirname + ‘/js’));
app.use(‘/dist’, express.static(__dirname + ‘/../dist’));
app.use(‘/css’, express.static(__dirname + ‘/css’));
app.use(‘/partials’, express.static(__dirname + ‘/partials’));
app.all(‘/*’, function(req, res, next) {
// Just send the index.html for other files to support HTML5Mode
res.sendFile(‘index.html’, { root: __dirname });
});
app.listen(3006); //the port you want to use
Also, read this great tutorial about Angular + Express

ASP.Net C# Rewrites
In Global.asax

private const string ROOT_DOCUMENT = “/default.aspx”;
protected void Application_BeginRequest( Object sender, EventArgs e )
{

//in  case rest API calling from angularJS and api string in url
//check URL don’t have /api/ then only execute following code

string url = Request.Url.LocalPath;
if ( !System.IO.File.Exists( Context.Server.MapPath( url ) ) )
Context.RewritePath( ROOT_DOCUMENT );

}

If Production IIS server throw an error <rewrite> invalid child element in <system.webServer> .

Install URL Rewrite module tool on Server.

Read more about
http://www.iis.net/learn/extensions/url-rewrite-module/using-the-url-rewrite-module

More About URL ReWrite
http://www.iis.net/downloads?tabid=34&g=6&i=1691

Download Tool from
Download the x86 version of the URL Rewrite module
Download the x64 version of the URL Rewrite module

ReWrite will work on II7 or higher

====

Enjoy!!