Sub topic 14
Path vs Hash Location Strategies
Earlier chapters covered how the router matches URLs to components. This chapter covers how those URLs are written in the browser's address bar and what that choice means for your server. Angular has two location strategies. The default is the path strategy, which produces URLs like /products/42. The other is the hash strategy, which produces URLs like /#/products/42. Both run the same route table. They differ in how the server, the browser, and tools outside your app treat the URL.
This chapter assumes you can configure routes with provideRouter, know how RouterLink and Router.navigate work, and have deployed a built Angular app to a web server at least once.
What a Location Strategy Does
A location strategy sits between the router and the browser. When the router navigates, it asks the strategy to write the new URL into the address bar. When the user presses Back, edits the URL, or reloads, the strategy reads the URL and gives the router a path to match.
The router never deals with the browser directly. It calls the Location service, and Location passes the call to whichever LocationStrategy is provided. That is why you can switch strategies without editing a single route or link: routerLink="/products/42" works the same under both.
PathLocationStrategy: The Default
PathLocationStrategy uses the HTML5 History API. It calls history.pushState() to change the URL without loading a new page. The address bar shows https://shop.example.com/products/42, which looks the same as a server-rendered site.
You get this strategy without asking for it:
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { AppComponent } from './app.component';
import { routes } from './app.routes';
bootstrapApplication(AppComponent, {
providers: [provideRouter(routes)] // PathLocationStrategy is used by default
});The Deep-Link Problem
While the user clicks around inside the app, no request goes to the server. The problem comes when the browser does send a request for a route path. That happens on a page reload, a bookmarked link, a link pasted into a new tab, or a link from an email. The browser sends GET /products/42. The server has no file at that path, so it returns 404, and the Angular app never loads.
The fix is a server fallback rule: any request that does not match a real file returns index.html. Angular then boots, reads /products/42 from the address bar, and renders the right component.
Configuring the Server Fallback
For nginx, try_files serves the file if it exists and otherwise falls back to index.html:
server {
listen 80;
root /usr/share/nginx/html;
location / {
try_files $uri $uri/ /index.html;
}
}For a Node server built with Express, put the static middleware first and the fallback after it. The fallback skips API paths and non-GET requests, so a mistyped API URL still returns a real 404 and does not come back as HTML:
// server.js
const express = require('express');
const path = require('path');
const app = express();
const dist = path.join(__dirname, 'dist/my-app/browser');
app.use(express.static(dist));
app.use((req, res, next) => {
if (req.method !== 'GET' || req.path.startsWith('/api/')) {
return next();
}
res.sendFile(path.join(dist, 'index.html'));
});
app.listen(8080, () => console.log('Listening on http://localhost:8080'));Static hosts such as Firebase Hosting, Netlify, Azure Static Web Apps, and Amazon S3 with CloudFront each have their own rewrite or custom-error setting that does the same job. On S3 with CloudFront, a common setup maps 403 and 404 errors to /index.html with a 200 status.
The Base Href
The path strategy resolves URLs against the <base href> tag in index.html. The router uses it to separate the app's root from the route path. The browser uses it to resolve relative URLs for scripts, styles, and images.
<base href="/">If the app is served from a subfolder such as https://example.com/shop/, build it with a matching base:
ng build --base-href /shop/When the base href is wrong, the usual symptoms are a blank page with 404s for the JavaScript bundles, or routes that match on the first load but break after a reload. You can also set the base in code with the APP_BASE_HREF token. This is useful in server-side rendering or when the HTML cannot be edited:
import { APP_BASE_HREF } from '@angular/common';
// in the providers array:
{ provide: APP_BASE_HREF, useValue: '/shop/' }HashLocationStrategy: The Opt-In Alternative
HashLocationStrategy puts the route after a #: https://shop.example.com/#/products/42. Browsers never send the fragment (the part after #) to the server. Every request is for /, which already serves index.html, so no server configuration is needed.
Enable it with the withHashLocation() router feature:
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, withHashLocation } from '@angular/router';
import { AppComponent } from './app.component';
import { routes } from './app.routes';
bootstrapApplication(AppComponent, {
providers: [provideRouter(routes, withHashLocation())]
});Older code does the same thing by providing the strategy class directly. You will still see this form in apps that use NgModules:
import { HashLocationStrategy, LocationStrategy } from '@angular/common';
// in the providers array:
{ provide: LocationStrategy, useClass: HashLocationStrategy }Your routes, links, guards, and router.navigate() calls stay the same. routerLink="/products/42" renders as href="#/products/42" automatically.
Gotchas Specific to Hash URLs
- Fragments inside fragments. A route fragment such as
/docs#installbecomes/#/docs#install. The router still parsesinstallas the fragment, but the browser's native jump-to-anchor no longer works. Turn on Angular's own anchor scrolling withwithInMemoryScrolling({ anchorScrolling: 'enabled' }). - OAuth and OpenID Connect redirects. Some identity providers return tokens in the URL fragment, for example
#access_token=.... That collides with the hash-based route. Use the authorization code flow, which returns values in the query string, or register a redirect URI that your auth library handles before the router runs. - Server-side rendering. The server never receives the route, so it cannot render the requested page. SSR and prerendering require the path strategy.
- Analytics and SEO. Many analytics tools drop the fragment by default and record every page view as
/. Search engines also treat hash URLs as a single page.
Reading the Current URL Without Caring About the Strategy
Use Location from @angular/common instead of window.location when you need the current path or need to go back. Location returns the path with the strategy applied, so the same code works under both strategies:
import { Component, inject } from '@angular/core';
import { Location } from '@angular/common';
@Component({
selector: 'app-back-button',
standalone: true,
template: `<button (click)="goBack()">Back from {{ current }}</button>`
})
export class BackButtonComponent {
private location = inject(Location);
current = this.location.path(); // '/products/42' under either strategy
goBack(): void {
this.location.back();
}
}window.location.pathname returns /products/42 under the path strategy but / under the hash strategy. That difference is a common source of bugs after a team switches strategies.
Choosing a Strategy
| Concern | PathLocationStrategy | HashLocationStrategy |
|---|---|---|
| URL appearance | `/products/42` | `/#/products/42` |
| Server configuration | Fallback to `index.html` required | None |
| Server-side rendering and prerendering | Supported | Not possible |
| SEO and analytics | Works normally | Fragment often ignored |
| In-page anchors | Native behavior | Needs in-memory anchor scrolling |
| OAuth implicit-flow redirects | No conflict | Collides with token fragment |
| Static hosting with no rewrite rules | Breaks on reload | Works |
Use the path strategy unless you cannot control the server. The hash strategy fits apps on file shares or locked-down intranet servers, apps embedded in hybrid shells that load from file://, and internal tools where clean URLs do not matter.
Exercise
Your app uses the default strategy and works when users click through it, but reloading /orders/7 in production returns a 404 from the server. Locally with ng serve it works. Why, and what are two ways to fix it?
Show answer
The dev server already falls back to index.html, but the production server looks for a file at /orders/7 and finds none. Fix it by adding a fallback rule such as nginx try_files $uri $uri/ /index.html or a host rewrite to index.html, or by switching to the hash strategy with withHashLocation() so the browser only ever requests /.
Exercise
A team adds SSR to an app that uses withHashLocation(). Every server-rendered page shows the home component, whatever the URL. Explain the cause.
Show answer
The route lives in the fragment, and browsers never send the fragment to the server. The server sees every request as /, so it renders the home route. SSR needs PathLocationStrategy so the route path reaches the server.
Exercise
An app is deployed at https://example.com/portal/. Its bundles load, but after navigating to a route and reloading, the scripts return 404. What is most likely misconfigured?
Show answer
The base href is probably still /, so relative asset URLs resolve against the current route path or the site root instead of /portal/. Build with ng build --base-href /portal/ (or set <base href="/portal/">) and make sure the server's fallback serves /portal/index.html.