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>
Subscribe or Follow Me For Updates
Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.
- Follow me on Twitter at https://twitter.com/jason_watmore
- Subscribe on YouTube at https://www.youtube.com/JasonWatmore
- Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
- Follow me on GitHub at https://github.com/cornflourblue
- Feed formats available: RSS, Atom, JSON
Other than coding...
I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.
- Subscribe on YouTube at https://www.youtube.com/TinaAndJason
- Follow us on Instagram at https://www.instagram.com/tinaandjason
- Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
- Visit our website at https://tinaandjason.com.au
Need Some AngularJS Help?
Search fiverr to find help quickly from experienced AngularJS developers.