Redirect all requests using Express 3?

亡梦爱人 提交于 2019-12-22 08:43:54

问题


What is the best way to do this?

I'd like to redirect all requests from www.mysite.com to mysite.com

*.mysite.com to mysite.com would be ideal

I would think some type of middleware. I still hate this, because it seems so inelegant and slightly wasteful, but I think my only option is to do this server-side.


回答1:


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')));


来源:https://stackoverflow.com/questions/12116247/redirect-all-requests-using-express-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!