I am serving a static directory like so:
var app = express.createServer();
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
So I am not using routes at all. I would like to redirect example.com to www.example.com, is this possible using Express?
The following code preserve path while redirecting
Ex: http://foo.com/foo to 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'));
Alternatively, you can use a ready-made module for Express that does exactly what you want, e.g. node-force-domain.
See https://github.com/goloroden/node-force-domain for details.
Yes. This 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);
You can use 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 on npm: https://npmjs.org/package/express-force-domain
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With