Remove hash(#) in URL Angular 11
Asked Answered
E

1

6

I want to remove the # from the URL, but when I remove it, there will be a problem when I deploy it to the server. When the page is refreshed, will get a status of 404.

example

https: // a / user / (works)

https: // a / user / 1 (Not working)

app-routing.module.ts

    @NgModule({
  imports: [RouterModule.forRoot(routes)],
  providers: [
    {provide: LocationStrategy, useClass: PathLocationStrategy} 
  ],
  exports: [RouterModule]
})

app.module.ts

......
providers: [ Location, {provide: LocationStrategy, useClass: PathLocationStrategy}]

Please advise me what should I do.

Estis answered 23/2, 2021 at 3:55 Comment(0)
T
8

PathLocationStrategy is the default location strategy of Angular Routing, It should work and resolve your hash(#) problem.

There is no error in your code, double check below points

  1. RouterModule.forRoot(routes, { useHash: true }) //use Hash should not be there
  2. providers: [ // Below line is optional as default LocationStrategy is PathLocationStrategy {provide: LocationStrategy, useClass: PathLocationStrategy} ]

If you are only facing issue in server when deployed, Please check the entry point configuration in the server. It should be index.html file.

NOTE: when using PathLocationStrategy you need to configure your web server to serve index.html (app's entry point) for all requested locations.

Also check the <base href="/"> in index.html and at the backend server, we must render the index.html file according to path.

Tilt answered 23/2, 2021 at 4:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.