3

我是流星新手。自动重定向会很酷

例子.com

www.example.com

. 任何人都可以帮忙吗?

4

3 回答 3

7

我知道这是 2 岁,但它没有被接受的答案,所以我提供了一个完整的答案:

WebApp.connectHandlers.use(function(req, res, next) {

  // Check if request is for non-www address
  if (req.headers && req.headers.host.slice(0, 4) !== 'www.') {

    // Add www. from host
    var newHost = 'www.' + req.headers.host

    // Redirect to www. version URL
    res.writeHead(301, {
      // Hard-coded protocol because req.protocol not available
      Location: 'http://' + newHost + req.originalUrl
    });
    res.end();

  } else {
    // Continue with the application stack
    next();
  }
});

您可以使用以下代码进行相反的方向(从 www 到非 www):

WebApp.connectHandlers.use(function(req, res, next) {

  // Check if request is for non-www address
  if (req.headers && req.headers.host.slice(0, 4) === 'www.') {

    // Remove www. from host
    var newHost = req.headers.host.slice(4);

    // Redirect to non-www URL
    res.writeHead(301, {
    // Hard-coded protocol because req.protocol not available
      Location: 'http://' + newHost + req.originalUrl
    });
    res.end();

  } else {
    // Continue with the application stack
    next();
  }
});
于 2015-10-27T20:35:02.663 回答
0

您可以通过添加一个中间件来做到这一点。这应该让你开始:

WebApp.connectHandlers.use(function(req, res, next) {

    /* Check if request is for non-www address */
    if(...) {
        /* Redirect to the proper address */
        res.writeHead(301, {
            Content-Type': 'text/html; charset=UTF-8',
            Location: correctURL,
        });
        res.end("Moved to: " + correctURL);
        return;
    }

    /* Did not redirect - continue with the application stack */

    next();

});
于 2013-09-28T07:29:21.377 回答
0

我在客户端使用此代码:

Meteor.startup(function () {
    if (location.host.indexOf('www.domain.com') !== 0) {
        location = 'www.domain.com';
    }
});

它非常简单和工作。我希望这能回答你的问题。谢谢

于 2016-04-06T11:55:17.467 回答