Episode 25 of 25

Pretty URLs

Learn how to remove the hash from AngularJS URLs using HTML5 mode.

By default, AngularJS URLs use a hash (#): http://example.com/#/about. You can remove the hash to get pretty URLs: http://example.com/about.

Enabling HTML5 Mode

app.config(function($locationProvider) {
    $locationProvider.html5Mode(true);
});

Add the Base Tag

You must add a <base> tag in <head>:

<head>
    <base href="/">
    <!-- ... other tags -->
</head>

Update Navigation Links

<!-- Before (hash URLs) -->
<a href="#/">Home</a>
<a href="#/about">About</a>

<!-- After (pretty URLs) -->
<a href="/">Home</a>
<a href="/about">About</a>

Server Configuration

With pretty URLs, your server must be configured to return index.html for all routes. Otherwise, refreshing a page like /about will return a 404.

Apache (.htaccess):

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.html [L]

Nginx:

location / {
    try_files $uri $uri/ /index.html;
}

Node.js/Express:

app.get('*', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});

Summary

  • Enable $locationProvider.html5Mode(true)
  • Add <base href="/"> to the head
  • Update links to remove #
  • Configure your server to handle all routes

Congratulations! You've completed the AngularJS tutorial series. You now have a solid foundation to build dynamic single-page applications! 🎉