title: Non www to www redirection in node server not working properly
body: <p>I have to following code to redirect non www requests to www on Node server :</p>
  
  <pre><code>app.get('/*', function(req, res, next) {
   if (req.headers.host.match(/^www/) === null ) res.redirect('https://www.' + 
   req.headers.host + req.url, 301);
   else next();
  });
  </code></pre>
  
  <p>But if the user enters foo.com, it's not redirected to www.foo.com. Instead if foo.com is refreshed, then it's being redirected to www.foo.com</p>
  
  <p>I've tried <a href="https://www.npmjs.com/package/node-force-domain" rel="nofollow noreferrer">ForceDomain</a> as well but the problem exists. Is there anything that am I doing wrong ?</p>
  
  <p>Following is the whole code :</p>
  
  <pre><code>var express=require('express');
  var httpsRedirect = require('express-https-redirect');
  path=require('path');
  bodyParser=require('body-parser');
  cors=require('cors');
  passport=require('passport');
  mongoose=require('mongoose');
  config=require('./config/database');
  app=express();
  app.use('/', httpsRedirect());
  port=3700;
  app.use(cors());
  app.use(bodyParser.json());
  app.use(passport.initialize());
  app.use(passport.session());
  require('./config/passport')(passport);
  var users=require('./routes/users');
  admin=require('./routes/admin');
  app.use('/users',users);
  app.use('/admin',admin);
  app.use(express.static(path.join(__dirname,'public')));
  app.listen(port,function(){console.log('Server logged on '+port)});
  mongoose.connect(config.database);
  mongoose.connection.on('connected',function(){
  });
  mongoose.connection.on('error',function(a){
   a&amp;&amp;console.log('Error'+a)
  });
  // Forcedomain to www
  
  app.get('/*', function(req, res, next) {
    if (req.headers.host.match(/^www/) === null ) res.redirect('https://www.' + req.headers.host + req.url, 301);
    else next();
  });
  
  app.get('*',function(a,b){
  b.sendFile(path.join(__dirname + '/public/index.html'))
  });
  </code></pre>