Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How would i get the server to redirect all the urls to index.html #66

Closed
benedikt-buchert opened this issue Nov 28, 2013 · 9 comments
Closed

Comments

@benedikt-buchert
Copy link

I want the server to redirect all urls to index.html, because I'm using the html 5 history api. Is there an elegant way to do this with connect?

@shama
Copy link
Member

shama commented Nov 28, 2013

Add your own middleware that points every url to the index.html file:

middleware: function(connect, options) {
  return [function(req, res) {
    require('fs').createReadStream('index.html').pipe(res);
  }]
}

@shama shama closed this as completed Nov 28, 2013
@shaekuronen
Copy link

As far as I can tell, this redirects every URL including links to js css files etc

Is there an easy way to duplicate the htaccess style, so that requests for actual files do not get redirected?

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

could easily be how I've config'd, so here's that below, thanks!

// start a node server
connect: {
  preview: {
    options: {
      port: 9000,
      keepalive: true,
      base: './dev',
      livereload: true,
      // https://github.com/gruntjs/grunt-contrib-connect/issues/66
      middleware: function(connect, options) {
        return [function(req, res) {
          require('fs').createReadStream('dev/index.html').pipe(res);
        }]
      }
    }
  },
  optimize: {
    options: {
      port: 9001,
      keepalive: true,
      base: './production',
      // https://github.com/gruntjs/grunt-contrib-connect/issues/66
      middleware: function(connect, options) {
        return [function(req, res) {
          require('fs').createReadStream('index.html').pipe(res);
        }]
      }
    }
  }
},

@shama
Copy link
Member

shama commented Apr 15, 2014

grunt-contrib-connect is just a wrapper for https://github.com/senchalabs/connect This task provides reasonable defaults for development. For more advanced use cases it is recommended to write your own connect middleware or even use connect directly.

middleware is a request and response stream. Based on the request, you give a response. The above example just gives index.html as the response for every request. Connect has a static middleware which will serve static files that correlate with the request. Using a combination of serve-static and your own middleware you can achieve your desired results.

@shaekuronen
Copy link

Thanks for the direction @shama

For anyone running into the same issue, I ended up using this strategy danburzo.ro/grunt/chapters/server/ by @danburzo

It would be super cool if something like this was an option w/ grunt-contrib-connect, though totally understand may not fit w/ project goals/scope

module.exports = function(grunt) {

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

  // Project configuration.
  grunt.initConfig({

    // start a node server
    connect: {
      preview: {
        options: {
          port: 9000,
          livereload: 35729,
          keepalive: true,
          base: './dev',
          hostname: 'localhost',

          // http://danburzo.ro/grunt/chapters/server/
          middleware: function(connect, options) {

            var middleware = [];

            // 1. mod-rewrite behavior
            var rules = [
                '!\\.html|\\.js|\\.css|\\.svg|\\.jp(e?)g|\\.png|\\.gif$ /index.html'
            ];
            middleware.push(rewrite(rules));

            // 2. original middleware behavior
            var base = options.base;
            if (!Array.isArray(base)) {
                base = [base];
            }
            base.forEach(function(path) {
                middleware.push(connect.static(path));
            });

            return middleware;

          }

        }
      }
    },

    watch: {
      dev: {
        files: 'dev/**/*',
        tasks: ['preview'],
        options: {
          debounceDelay: 250,
          livereload: true
        },
      }
    },

    jshint: {
      all: [
        'Gruntfile.js',
        'dev/js/site/**/*.js'
      ],
      options: {
        jshintrc: '.jshintrc',
      }
    }

  });

  // preview task
  grunt.registerTask('preview', [], function () {

    // load plugins for the task
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-contrib-watch');

    // execute the task
    grunt.task.run(
      'connect:preview'
    );

  });
  // end preview task

  // task
  grunt.registerTask('optimize', [], function () {

    // load plugins for the task
    grunt.loadNpmTasks('grunt-contrib-connect');

    // execute the task
    grunt.task.run(
      ''
    );

  });
  // end task

};

@doivosevic
Copy link

I got Warning: connect.static is not a function Use --force to continue.
Any ideas?

@vladikoff
Copy link
Member

@DominikDitoIvosevic see #191 (comment)

@doivosevic
Copy link

Yeah. This seems to be working for me tho

connect: {
  server: {
    options: {
      port: 9001,
      base: '',
      keepalive: true,
      // http://danburzo.ro/grunt/chapters/server/
      middleware: function(connect, options, middlewares) {
        // 1. mod-rewrite behavior
        var rules = [
            '!\\.html|\\.js|\\.css|\\.svg|\\.jp(e?)g|\\.png|\\.gif$ /index.html'
        ];
        middlewares.unshift(rewrite(rules));
        return middlewares;
      }
    }
  }
}

What I get is that the route stays the same in the address bar (i.e. '/admin') and my angular app from '/index.html' gets routed to '/admin' on reload so it is even more than I expected (I expected to be simply redirected and routed to '/'

@camsjams
Copy link

@DominikDitoIvosevic that's a simple fix - it's just a dev server to me, didn't want to go through too much hassle

@tandn37
Copy link

tandn37 commented Jul 11, 2019

nice solution guys

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants