Using grunt server, how can I redirect all requests to root url?

Charlie Martin picture Charlie Martin · Jun 13, 2013 · Viewed 29.5k times · Source

I am building my first Angular.js application and I'm using Yeoman.

Yeoman uses Grunt to allow you to run a node.js connect server with the command 'grunt server'.

I'm running my angular application in html5 mode. According to the angular docs, this requires a modification of the server to redirect all requests to the root of the application (index.html), since angular apps are single page ajax applications.

"Using [html5] 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 problem that I'm trying to solve is detailed in this question.

How can I modify my grunt server to redirect all page requests to the index.html page?

Answer

Zuriel picture Zuriel · Dec 12, 2013

First, using your command line, navigate to your directory with your gruntfile.

Type this in the CLI:

npm install --save-dev connect-modrewrite

At the top of your grunt file put this:

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

Now the next part, you only want to add modRewrite into your connect:

modRewrite(['!\\.html|\\.js|\\.svg|\\.css|\\.png$ /index.html [L]']),

Here is a example of what my "connect" looks like inside my Gruntfile.js. You don't need to worry about my lrSnippet and my ssIncludes. The main thing you need is to just get the modRewrite in.

        connect: {
        options: {
            port: 9000,
            // Change this to '0.0.0.0' to access the server from outside.
            hostname: '0.0.0.0',
        },
        livereload: {
            options: {
                middleware: function (connect) {
                return [
                        modRewrite(['!\\.html|\\.js|\\.svg|\\.css|\\.png$ /index.html [L]']),
                        lrSnippet,
                        ssInclude(yeomanConfig.app),
                        mountFolder(connect, '.tmp'),
                        mountFolder(connect, yeomanConfig.app)
                        ];
                }
            }
        },
        test: {
            options: {
                middleware: function (connect) {
                    return [
                    mountFolder(connect, '.tmp'),
                    mountFolder(connect, 'test')
                    ];
                }
            }
        },
        dist: {
            options: {
                middleware: function (connect) {
                    return [
                    mountFolder(connect, yeomanConfig.dist)
                    ];
                }
            }
        }
    },