From the first install angular come with hash URL routing and it’s defined in app-routing.module.ts
. To remove hash from URL we need to change useHash
key to false
. Angular runs it development application ng server and whenever we wanted to deploy the application we need a server like Apache or Nginx.
If we remove hash then we can not load other url’s of the application because it cannot route easily to handle this scenarios we use .htaccess
or nginx.conf
so that we can route all traffic to our index.html file.
So, remove the hash location strategy from app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{
path: "/",
component: LoginComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes,{useHash:false})],
exports: [RouterModule]
})
export class AppRoutingModule { }
So here we changed RouterModule.forRoot(routes,{useHash:true})
to RouterModule.forRoot(routes,{useHash:false})
.
Or we can remove the second parameter as below
RouterModule.forRoot(routes);
Deploy angular application without hash URL on server
By removing the hash from URL we won’t be able to access the other URLs of application except /
or index page.
So to access them we need add htaccess
rule on our Apache server as below
<IfModule mod_rewrite.c>
RewriteEngine On
# Redirection of requests to index.html
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(.*) index.html [NC,L]
</IfModule>
Now our old url was
http://localhost:8080/#/login
and we will be able to access out url without Hash as below.
http://localhost:8080/login