DEV Community

Cover image for Angular Routing Removing hash (#) on URL
manoj
manoj

Posted on • Updated on

Angular Routing Removing hash (#) on URL

In Angular 9 hide hash (#) from URL is an easy task.

In previous versions sometimes confusing/find difficulties in removing the hash (#) from the URL.

Steps below for a quicker solution.

  1. Remove useHash: true from router modules, By default it's false.
  2. Add (/)slash to base href in the index page
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
<base href="/">

Fix for restriction of redirection to siblings and children paths in the router.

Now its works fine in the dev environment.

For prod, we need to add rules in (.htaccess) file.
Below htaccess issue fix arises in prod, not in dev.

<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>
http://localhost:3000/#/login

After the above steps implemented, now a hash sign removed from URL.

http://localhost:3000/login

Top comments (2)

Collapse
 
vitalyt profile image
Vitaly Tomilov

If I make this change, my API stops working. It sends requests to the website at /api root, and the website forwards them into index.html because of this override. So it is an incomplete solution. Any idea how to fix this?

Collapse
 
surya_madhav_ profile image
Surya

Hi manoj.
When i removed the {useHash: true} it brings another error. When i reload the page i get this error "Cannot GET /dashboard/home". Are you aware of any fix for this?