Question

I'm using AngularJS routes and partials to establish the page structure of my site. I am using HTML5 mode to avoid the hashbang. Navigation from one page to the next works through clicking on the links, but when refreshing the page or typing the url directly I get a 404, page not found error. How do I correct this problem?

Here is the stripped down HTML:

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="utf-8">
    <title>site</title>
    <base href="/">
</head>
<body ng-controller="MyController">
    <a href="/home">Site</a>
    <ul>
        <li><a href="/home">Home</a></li>
        <li><a href="/about">About</a></li>
        <li><a href="/contact">Contact</a></li>
    </ul>

    <div ng-view></div>

    <script src="js/angular.min.js"></script>
    <script src="js/angular-route.min.js"></script>
    <script src="js/app.js"></script>

</body>
</html>

Here is my app.js:

angular.module('myApp', ['ngRoute'])
    .config(function($locationProvider, $routeProvider) {
        $locationProvider.html5Mode(true);
        $routeProvider.
            when('/home', { templateUrl: 'partials/home.html', }).
            when('/about', { templateUrl: 'partials/about.html', }).
            when('/contact', { templateUrl: 'partials/contact.html', }).
            otherwise({ redirectTo: '/home' });
    });

function MyController($scope) {

}

The partial pages just emit a single line:

home partial

or

about partial

or

contact partial

I've tried this on both IIS7 and Apache, with the same results each time.

Any assistance will be much appreciated. Thank you for your time.

Was it helpful?

Solution

This behavior sounds as if the server has not been configured to handle your use of html5 mode. Your server has no resources to serve for requests at paths such as /home, /about, and /contact. (Thus the 404.) You need to configure server side rewrites so that those requests will simply serve your index page. This way, if you paste in the url /about, the server serves the index page (which does exist) and your client side code takes care of displaying the "about" partial.

Even though it's a third party lib, the documentation for ui-router has great examples for a few server types (including Apache).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top