Since Express 3 doesn't use its own HTTP server (instead you pass your app to http.createServer
), it doesn't know what port it's running on unless you tell it. That said, you can do basically what you want to do with the following:
app.use(function(request, response, next) {
var newHost = request.host.replace(/^www\./, '');
if (request.host != newHost) {
// 301 is a "Moved Permanently" redirect.
response.redirect(301, request.protocol + "://" + newHost + request.url);
} else {
next();
}
});
You could export this in a module and wrap it in a generator that takes a port:
// no_www.js
module.exports = function(port) {
app.use(function(request, response, next) {
var newHost = request.host.replace(/^www\./, '');
if (request.host != newHost) {
var portStr = '';
if (request.protocol == 'http' && port != 80) portStr = ':' + port;
if (request.protocol == 'https' && port != 443) portSt r= ':' + port;
// 301 is a "Moved Permanently" redirect.
response.redirect(301, request.protocol + "://" + newHost + portStr + request.url);
} else {
next();
}
});
}
// app.js
var noWww = require('./no_www');
var app = express();
app.configure("development", function() {
app.set("port", 3000);
});
...
app.use(noWww(app.get('port')));