July 26 2016

AngularJS - Enable HTML5 Mode Page Refresh Without 404 Errors in NodeJS and IIS

NOTE: This fix also works for Angular 2 applications running on Express or IIS.

By setting html5mode to true in an AngularJS application it removes the hash (#) prefix from the angular virtual urls, a side effect of this is that if you try to navigate directly to a deep link in your angular app or refresh an internal page you may get a 404 page not found error. This is because the web server receiving the request looks for a resource matching the full url on the server, which doesn't exist because the angular portion of the url refers to a route in your angular application and needs to be handled in the client browser.

The way to fix this is by rewriting all virtual urls to the main angular index.html file, below are examples of how to do this in NodeJS and IIS.


AngularJS + NodeJS/ExpressJS - Routes to prevent 404 error after page refresh in html5mode

For angular applications running under NodeJS and ExpressJS

var express = require('express');
var path = require('path');
var router = express.Router();

// serve angular front end files from root path
router.use('/', express.static('app', { redirect: false }));

// rewrite virtual urls to angular app to enable refreshing of internal pages
router.get('*', function (req, res, next) {
    res.sendFile(path.resolve('app/index.html'));
});

module.exports = router;


AngularJS + IIS - URL Rewrite Rule to prevent 404 error after page refresh in html5mode

For angular applications running under IIS on Windows

<rewrite>
  <rules>
    <rule name="AngularJS" stopProcessing="true">
      <match url=".*" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Rewrite" url="/" />
    </rule>
  </rules>
</rewrite>

Sponsored by