193

I want to enable HTML5 mode for my app. I have put the following code for the configuration, as shown here:

return app.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) {

    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix = '!';

    $routeProvider.when('/', {
        templateUrl: '/views/index.html',
        controller: 'indexCtrl'
    });
    $routeProvider.when('/about',{
        templateUrl: '/views/about.html',
        controller: 'AboutCtrl'
    });

As you can see, I used the $locationProvider.html5mode and I changed all my links at the ng-href to exclude the /#/.

The Problem

At the moment, I can go to localhost:9000/ and see the index page and navigate to the other pages like localhost:9000/about.

However, the problem occurs when I refresh the localhost:9000/about page. I get the following output: Cannot GET /about

If I look at the network calls:

Request URL:localhost:9000/about
Request Method:GET

While if I first go to localhost:9000/ and then click on a button that navigates to /about I get:

Request URL:http://localhost:9000/views/about.html

Which renders the page perfectly.

How can I enable angular to get the correct page when I refresh?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Dieter De Mesmaeker
  • 2,156
  • 2
  • 14
  • 14

23 Answers23

99

From the angular docs

Server side
Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)

The reason for this is that when you first visit the page (/about), e.g. after a refresh, the browser has no way of knowing that this isn't a real URL, so it goes ahead and loads it. However if you have loaded up the root page first, and all the javascript code, then when you navigate to /about Angular can get in there before the browser tries to hit the server and handle it accordingly

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
James Sharp
  • 1,494
  • 9
  • 8
  • 21
    When it says "you have to rewrite all your links to the entry point of your application (e.g. index.html)" what does this mean? Does it mean I have to go into my `$routeProvider` and change the paths of each `templateUrl` e.g. from `templateUrl : '/views/about.html',` to `templateUrl : 'example.com/views/about.html',`? –  Jul 27 '13 at 20:24
  • 7
    No, your rules in $routeProvider should stay as they are. The answer refers to "server side". It refers to changing the routing on the server that provides your angular html pages. Before each request gets to your angular app, it has to pass first through server-side routing, which should rewrite all requests to point to your angular app entry point (e.g. 'index.html', or '/', depending how your angular routes work). – marni Feb 01 '14 at 15:27
  • In case if I serve my minified index.html via some CDN than how will this routing mechanism will executes ?? – CrazyGeek Oct 17 '14 at 09:23
  • You'll need to make sure all requests somehow get to index.html. Maybe the CDN will allow you to configure this or you'll have to get the CDN to pass through all requests to some origin server that does this itself (e.g. point your CDN at simple nginx server that always serves up index.html regardless of the path). However if you're frequently updating index.html then having a CDN in the way may be more trouble than its worth. – James Sharp Nov 04 '14 at 12:18
  • what type of changes i can in server side. Is i change something in .htaccess file – asb14690 Jan 21 '15 at 11:16
  • 1
    yes - have a look at http://stackoverflow.com/questions/22739455/htaccess-redirect-for-angular-routes – James Sharp Jan 22 '15 at 10:18
  • 5
    Good article for apache, there is an htaccess exemple : https://ngmilk.rocks/2015/03/09/angularjs-html5-mode-or-pretty-urls-on-apache-using-htaccess/ – Alcalyn Jun 03 '15 at 19:27
  • After fixing server side with node/express route config I'm still seeing a different error trying to refresh at a given url. So base is /report and if I navigate from base to /report/test it works, but refresh, server side does go to to base but I get this angular error Error: $injector:modulerr Module Error. Seems like some timing issue still, like Angular having problems initiating from non base location – bjm88 Jan 08 '16 at 12:16
  • how can i configure it in localhost – byteC0de Mar 30 '18 at 05:45
64

There are few things to set up so your link in the browser will look like http://yourdomain.com/path and these are your angular config + server side

1) AngularJS

$routeProvider
  .when('/path', {
    templateUrl: 'path.html',
  });
$locationProvider
  .html5Mode(true);

2) server side, just put .htaccess inside your root folder and paste this

RewriteEngine On 
Options FollowSymLinks

RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /#/$1 [L]

More interesting stuff to read about html5 mode in angularjs and the configuration required per different environment https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode Also this question might help you $location / switching between html5 and hashbang mode / link rewriting

Community
  • 1
  • 1
lokers
  • 2,106
  • 2
  • 18
  • 19
37

I had a similar problem and I solved it by:

  • Using <base href="/index.html"> in the index page

  • Using a catch all route middleware in my node/Express server as follows (put it after the router):

app.use(function(req, res) {
    res.sendfile(__dirname + '/Public/index.html');
});

I think that should get you up and running.

If you use an apache server, you might want to mod_rewrite your links. It is not difficult to do. Just a few changes in the config files.

All that is assuming you have html5mode enabled on angularjs. Now. note that in angular 1.2, declaring a base url is not recommended anymore actually.

Taye
  • 797
  • 1
  • 10
  • 15
  • 1
    This solution worked for me with setting: `` and adding the Express routing you suggested. Mucho thanks. – Gilad Peleg Nov 11 '13 at 19:13
  • Tahir Chad, did you still need to use a serverside url-rewrite after implementing the ``? – Cody Jan 29 '14 at 21:40
  • Yes, you can see url rewriting as a way to set the base url of your application/website in stone (domain included). The 'base url' html statement is just a way to ensure that all relative links are correctly derived from the same base. Base url is not absolutely necessary if your links are absolute. – Taye Feb 08 '14 at 00:13
  • Where should I make the express change in cordova app? – Sam Mar 30 '15 at 14:21
  • 1
    When I use this, I just see the html code itself on the page, not rendered as an actual page. – Noah May 30 '15 at 08:18
  • 2
    This answer deserves triple stars! Thanks for providing such a straightforward answer. Everyone else just repeats the same line about "needing to do server redirecting". – Ahmed Haque Nov 11 '15 at 18:17
  • Nice answer, it appears to be the only one suitable for an Angular2 Chrome extension, using a wildcard to catch missing routes. – Standaa - Remember Monica Oct 24 '16 at 10:57
  • but due to this EVERY http request will have index file,Like eg : /getJsonFromServer - an http request that returns json but due to this configuration it will also return index page – vijay Feb 28 '17 at 13:36
  • I suggest you put right after not on end of . Because I had css that needed to be served from node.js and it didn't work when it was before the base tag – ta4ka Mar 15 '17 at 15:29
27

Solution for BrowserSync and Gulp.

From https://github.com/BrowserSync/browser-sync/issues/204#issuecomment-102623643

First install connect-history-api-fallback:

npm --save-dev install connect-history-api-fallback

Then add it to your gulpfile.js:

var historyApiFallback = require('connect-history-api-fallback');

gulp.task('serve', function() {
  browserSync.init({
    server: {
      baseDir: "app",
      middleware: [ historyApiFallback() ]
    }
  });
});
Oscar
  • 1,250
  • 13
  • 19
  • Oh snap! Finally relief from Angular view development! And as a bonus, standard URLs (without a hash-bang) route too! Thank you! – Modular Jan 05 '16 at 18:15
  • 1
    Works like a charm... Thanks a lot! – Nishanth Nair Mar 29 '16 at 19:49
  • 1
    If you're using a specific port (i.e. the Ionic blank template runs on port 8100), just add an additional property after server i.e. ```server: { ... }, port: 8100```, then just add the ```serve``` task to your default gulp task (i.e. ```gulp.task('default', ['sass', 'serve']);```), and then you can run the app without the ```Cannot GET ...``` browser errors when you refresh the page by running ```gulp``` . Note that running the server with ```ionic serve``` still encounters the errors. – Luke Schoen Jul 04 '16 at 02:43
  • This works well when I use development browsersync, in prod I am running the application as express app and redirecting all the route to angular app as app.get('*', function(req, res) { req.session.valid = true; res.redirect('/'); }); The page does not load when give the path directly ? – Mr X Dec 30 '17 at 16:25
15

You need to configure your server to rewrite everything to index.html to load the app:

https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#wiki-how-to-configure-your-server-to-work-with-html5mode

grant
  • 4,325
  • 2
  • 24
  • 20
  • 1
    Perfect, problem for me was using Laravel Forge to provision the server, which had the relevant nginx line as `try_files $uri $uri/ /index.php?...` instead of the needed `index.html`. Thanks for the link! – CJ Thompson Oct 02 '14 at 21:07
  • Should be top answer, Gives every situation no matter your server. Worked perfectly with NodeJS – Joe Lloyd Sep 19 '15 at 20:19
10

I wrote a simple connect middleware for simulating url-rewriting on grunt projects. https://gist.github.com/muratcorlu/5803655

You can use like that:

module.exports = function(grunt) {
  var urlRewrite = require('grunt-connect-rewrite');

  // Project configuration.
  grunt.initConfig({
    connect: {
      server: {
        options: {
          port: 9001,
          base: 'build',
          middleware: function(connect, options) {
            // Return array of whatever middlewares you want
            return [
              // redirect all urls to index.html in build folder
              urlRewrite('build', 'index.html'),

              // Serve static files.
              connect.static(options.base),

              // Make empty directories browsable.
              connect.directory(options.base)
            ];
          }
        }
      }
    }
  })
};
Murat Çorlu
  • 8,207
  • 5
  • 53
  • 78
  • Is there a manual way to accomplish URL re-writing in the `$routeProvider`? –  Jul 27 '13 at 20:26
  • 1
    I get `urlRewrite` is not defined warning when trying to run it, and I'm having a hard time finding the right connect with rewrite that I can use. –  Dec 12 '14 at 19:14
  • Shows me an error "Object build has no method 'initConfig' Use --force to continue." – edonbajrami Jul 18 '15 at 11:57
8

If you are in .NET stack with MVC with AngularJS, this is what you have to do to remove the '#' from url:

  1. Set up your base href in your _Layout page: <head> <base href="/"> </head>

  2. Then, add following in your angular app config : $locationProvider.html5Mode(true)

  3. Above will remove '#' from url but page refresh won't work e.g. if you are in "yoursite.com/about" page refresh will give you a 404. This is because MVC does not know about angular routing and by MVC pattern it will look for a MVC page for 'about' which does not exists in MVC routing path. Workaround for this is to send all MVC page request to a single MVC view and you can do that by adding a route that catches all url


routes.MapRoute(
        name: "App",
        url: "{*url}",
        defaults: new { controller = "Home", action = "Index" }
    );
Mo.
  • 26,306
  • 36
  • 159
  • 225
Maksood
  • 1,180
  • 14
  • 19
8

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

For angular 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>

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

For angular running under Node/Express

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;

More info at: AngularJS - Enable HTML5 Mode Page Refresh Without 404 Errors in NodeJS and IIS

Jason Watmore
  • 4,521
  • 2
  • 32
  • 36
  • Thanks, the IIS rules helped me with an angular2 app deployed in azure which was failing to direct to a child route. – bitsprint Sep 01 '16 at 13:42
  • I cannot thank you enough for the solution for IIS (localhost in VS 2013). Banged my head long enough in frustration, finally found this answer. Worked like a charm. – Florida G. Sep 30 '16 at 01:46
5

As others have mentioned, you need to rewrite routes on the server and set <base href="/"/>.

For gulp-connect:

npm install connect-pushstate

var gulp = require('gulp'),
  connect = require('gulp-connect'),
  pushState = require('connect-pushstate/lib/pushstate').pushState;
...
connect.server({
  ...
  middleware: function (connect, options) {
    return [
      pushState()
    ];
  }
  ...
})
....
Brett
  • 2,706
  • 7
  • 33
  • 49
4

I am using apache (xampp) on my dev environment and apache on the production, add:

errorDocument 404 /index.html

to the .htaccess solve for me this issue.

crlshn
  • 87
  • 8
4

For Grunt and Browsersync use connect-modrewrite here

var modRewrite = require('connect-modrewrite');    


browserSync: {
            dev: {
                bsFiles: {

                    src: [
                        'app/assets/css/*.css',
                        'app/*.js',
                        'app/controllers/*.js',
                        '**/*.php',
                        '*.html',
                        'app/jade/includes/*.jade',
                        'app/views/*.html',
               ],
            },
        options: {
            watchTask: true,
            debugInfo: true,
            logConnections: true,
            server: {
                baseDir :'./',
                middleware: [
                       modRewrite(['!\.html|\.js|\.jpg|\.mp4|\.mp3|\.gif|\.svg\|.css|\.png$ /index.html [L]'])
                ]
            },

            ghostMode: {
                scroll: true,
                links: true,
                forms: true
                    }
                }
            }
        },
MrThunder
  • 725
  • 12
  • 21
  • there are 15 above this answer that were a waist of time. 1. `npm install connect-modrewrite --save` 2. `require in gruntfile` 3. copy the above server obj – Omar Sep 12 '17 at 19:50
  • Thanks this worked for me in gulp 4 with browserSync setup. – Abdeali Chandanwala Jun 28 '19 at 13:02
  • Glad it helped @Abdeali Chandanwala! – MrThunder Jul 02 '19 at 18:28
  • @Omar I disagree with you, less advanced users such as myself benefit from seeing how to add it to the gulpfile. It is best to remember that people have different levels of knowledge and just writing require in gruntfile would not be helpful as I would be assuming that they understand how to add it to gulp. – MrThunder Jul 02 '19 at 18:28
3

I solved to

test: {
        options: {
          port: 9000,
          base: [
            '.tmp',
            'test',
            '<%= yeoman.app %>'
          ],
         middleware: function (connect) {
                  return [
                      modRewrite(['^[^\\.]*$ /index.html [L]']),
                      connect.static('.tmp'),
                      connect().use(
                          '/bower_components',
                          connect.static('./bower_components')
                      ),
                      connect.static('app')
                  ];
              }
        }
      },
Silvio Troia
  • 1,439
  • 19
  • 36
3

I'm answering this question from the larger question:

When I add $locationProvider.html5Mode(true), my site will not allow pasting of urls. How do I configure my server to work when html5Mode is true?

When you have html5Mode enabled, the # character will no longer be used in your urls. The # symbol is useful because it requires no server side configuration. Without #, the url looks much nicer, but it also requires server side rewrites. Here are some examples:

For Express Rewrites with AngularJS, you can solve this with the following updates:

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

and

<!-- FOR ANGULAR ROUTING -->
<base href="/">

and

app.use('/',express.static(__dirname + '/public'));
Adam B
  • 3,775
  • 3
  • 32
  • 42
Ironheartbj18
  • 87
  • 1
  • 4
  • 12
2

I believe your issue is with regards to the server. The angular documentation with regards to HTML5 mode (at the link in your question) states:

Server side Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)

I believe you'll need to setup a url rewrite from /about to /.

lucuma
  • 18,247
  • 4
  • 66
  • 91
  • Thank you for your answer. So when I am on the about page and I refresh, the server should rewrite the url to / ? The problem is that I work with a rails backend that is on a different domain. All communication is by API calls. How would I do those URL rewrites? – Dieter De Mesmaeker May 15 '13 at 16:52
  • The thing is your app is availabe at your server route of / so when you refresh a url that is /about the browser will request from your server whatever page is at /about (in this case you have no pages there so you need to redirect those back). – lucuma May 15 '13 at 16:54
2

We had a server redirect in Express:

app.get('*', function(req, res){
    res.render('index');
});

and we were still getting page-refresh issues, even after we added the <base href="/" />.

Solution: make sure you're using real links in you page to navigate; don't type in the route in the URL or you'll get a page-refresh. (silly mistake, I know)

:-P

Cody
  • 9,785
  • 4
  • 61
  • 46
  • but due to this EVERY http request will have index file,Like eg : /getJsonFromServer - an http request that returns data but due to this configuration it will also return index page – vijay Feb 28 '17 at 13:34
1

Finally I got a way to to solve this issue by server side as it's more like an issue with AngularJs itself I am using 1.5 Angularjs and I got same issue on reload the page. But after adding below code in my server.js file it is save my day but it's not a proper solution or not a good way .

app.use(function(req, res, next){
  var d = res.status(404);
     if(d){
        res.sendfile('index.html');
     }
});
Anil Yadav
  • 1,086
  • 7
  • 18
1

I have resolved the issue by adding below code snippet into node.js file.

app.get("/*", function (request, response) {
    console.log('Unknown API called');
    response.redirect('/#' + request.url);
});

Note : when we refresh the page, it will look for the API instead of Angular page (Because of no # tag in URL.) . Using the above code, I am redirecting to the url with #

0

I have found even better Grunt plugin, that works if you have your index.html and Gruntfile.js in the same directory;

https://npmjs.org/package/grunt-connect-pushstate

After that in your Gruntfile:

 var pushState = require('grunt-connect-pushstate/lib/utils').pushState;


    connect: {
    server: {
      options: {
        port: 1337,
        base: '',
        logger: 'dev',
        hostname: '*',
        open: true,
        middleware: function (connect, options) {
          return [
            // Rewrite requests to root so they may be handled by router
            pushState(),
            // Serve static files
            connect.static(options.base)
          ];
        }
      },
    }
},
Michał Lach
  • 1,291
  • 4
  • 18
  • 37
0
I solved same problem using modRewrite.  
AngularJS is reload page when after # changes.  
But HTML5 mode remove # and invalid the reload.  
So we should reload manually.
# install connect-modrewrite
    $ sudo npm install connect-modrewrite --save

# gulp/build.js
    'use strict';
    var gulp = require('gulp');
    var paths = gulp.paths;
    var util = require('util');
    var browserSync = require('browser-sync');
    var modRewrite  = require('connect-modrewrite');
    function browserSyncInit(baseDir, files, browser) {
        browser = browser === undefined ? 'default' : browser;
        var routes = null;
        if(baseDir === paths.src || (util.isArray(baseDir) && baseDir.indexOf(paths.src) !== -1)) {
            routes = {
                '/bower_components': 'bower_components'
            };
        }

        browserSync.instance = browserSync.init(files, {
            startPath: '/',
            server: {
            baseDir: baseDir,
            middleware: [
                modRewrite([
                    '!\\.\\w+$ /index.html [L]'
                ])
            ],
            routes: routes
            },
            browser: browser
        });
    }
keiwt
  • 499
  • 5
  • 5
0

I had the same problem with java + angular app generated with JHipster. I solved it with Filter and list of all angular pages in properties:

application.yml:

angular-pages:
  - login
  - settings
...

AngularPageReloadFilter.java

public class AngularPageReloadFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.getRequestDispatcher("index.html").forward(request, response);
    }
}

WebConfigurer.java

private void initAngularNonRootRedirectFilter(ServletContext servletContext,
                                              EnumSet<DispatcherType> disps) {
    log.debug("Registering angular page reload Filter");
    FilterRegistration.Dynamic angularRedirectFilter =
            servletContext.addFilter("angularPageReloadFilter",
                    new AngularPageReloadFilter());
    int index = 0;
    while (env.getProperty("angular-pages[" + index + "]") != null) {
        angularRedirectFilter.addMappingForUrlPatterns(disps, true, "/" + env.getProperty("angular-pages[" + index + "]"));
        index++;
    }
    angularRedirectFilter.setAsyncSupported(true);
}

Hope, it will be helpful for somebody.

Igor Zboichik
  • 559
  • 5
  • 9
0

Gulp + browserSync:

Install connect-history-api-fallback via npm, later config your serve gulp task

var historyApiFallback = require('connect-history-api-fallback');

gulp.task('serve', function() {
  browserSync.init({
    proxy: {
            target: 'localhost:' + port,
            middleware: [ historyApiFallback() ]
        }
  });
});
Oscar Caicedo
  • 130
  • 1
  • 6
0

Your server side code is JAVA then Follow this below steps

step 1 : Download urlrewritefilter JAR Click Here and save to build path WEB-INF/lib

step 2 : Enable HTML5 Mode $locationProvider.html5Mode(true);

step 3 : set base URL <base href="/example.com/"/>

step 4 : copy and paste to your WEB.XML

 <filter>
     <filter-name>UrlRewriteFilter</filter-name>
 <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

step 5 : create file in WEN-INF/urlrewrite.xml

 <urlrewrite default-match-type="wildcard">


    <rule>
            <from>/</from>
            <to>/index.html</to>
        </rule>

    <!--Write every state dependent on your project url-->
    <rule>
            <from>/example</from>
            <to>/index.html</to>
        </rule>
    </urlrewrite>
0

I have this simple solution I have been using and its works.

In App/Exceptions/Handler.php

Add this at top:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

Then inside the render method

public function render($request, Exception $exception)
{
    .......

       if ($exception instanceof NotFoundHttpException){

        $segment = $request->segments();

        //eg. http://site.dev/member/profile
        //module => member
        // view => member.index
        //where member.index is the root of your angular app could be anything :)
        if(head($segment) != 'api' && $module = $segment[0]){
            return response(view("$module.index"), 404);
        }

        return response()->fail('not_found', $exception->getCode());

    }
    .......

     return parent::render($request, $exception);
}
Emeka Mbah
  • 16,745
  • 10
  • 77
  • 96