If you have an old angular app that is still using hash-based routing via the HashLocationStrategy, you can safely migrate to modern PathLocationStrategy routing without breaking existing bookmarks or SEO.
- Add this snippet to your
AppComponent
>ngOnInit
:
this.router.events
.pipe(filter((event) => event instanceof NavigationStart && /^\/#/.test(event.url)))
.subscribe((event: NavigationStart) => this.router.navigateByUrl(event.url.replace('/#', '')));
Note that router.navigate
will strip any query params. I used router.navigateByUrl
instead.
- You can now safely turn off
useHash
:
RouterModule.forRoot(routes, { useHash: false })
Now, if you hit a URL like https://example.com/#/foo/bar
, the router will automatically redirect to https://example.com/foo/bar
. This will allow you to incrementally migrate your app to modern routing without breaking existing links.