使用Express 3重定向所有请求? [英] Redirect all requests using Express 3?

查看:116
本文介绍了使用Express 3重定向所有请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行此操作的最佳方法是什么?

What is the best way to do this?

我要重定向 www.mysite.com mysite.com

*。mysite.com mysite.com 将是理想的

我认为某种中间件。我仍然讨厌这样做,因为它看起来如此优雅且有点浪费,但是我认为我唯一的选择是在服务器端进行操作。

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.

推荐答案

由于Express 3不使用其自己的HTTP服务器(而是将您的应用传递给 http.createServer ),因此它不知道它在哪个端口上运行,除非你告诉它。也就是说,您基本上可以执行以下操作:

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

这篇关于使用Express 3重定向所有请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆