Redirect non-www to www using Node.js and Express

I maintain a static directory, for example:

var app = express.createServer(); app.configure(function(){ app.use(express.static(__dirname + '/public')); }); 

Therefore, I do not use routes at all. I would like to redirect example.com to www.example.com, is this possible with Express?

+7
source share
4 answers

Yes. That should do it.

 var express = require("express"); var app = express.createServer(); var port = 9090; app.all(/.*/, function(req, res, next) { var host = req.header("host"); if (host.match(/^www\..*/i)) { next(); } else { res.redirect(301, "http://www." + host); } }); app.use(express.static(__dirname + "/public")); app.listen(port); 
+9
source

Alternatively, you can use a ready-made module for Express that does exactly what you want, for example. node-force domain.

See https://github.com/goloroden/node-force-domain for more details.

+8
source

The following code saves the path when redirecting

Example: http://foo.com/foo at http://www.foo.com/foo

  var app = express.createServer(); self.app.all(/.*/, function(req, res, next) { var host = req.header("host"); if (host.match(/^www\..*/i)) { next(); } else { res.redirect(301, "http://www." + host + req.url); } }); app.use('/',express.static('public')); 
+7
source

You can use the express-force-domain package from npm:

 //install npm install express-force-domain ///app.js app.all('*', require('./express-force-domain')('http://www.example.com') ); 

Package at npm: https://npmjs.org/package/express-force-domain

+2
source

All Articles