【问题标题】:How to redirect from non www to www in meteor.js app如何在meteor.js应用程序中从非www重定向到www
【发布时间】:2013-09-27 21:20:51
【问题描述】:

我是流星新手。 从

自动重定向会很酷

example.com

www.example.com

。 有人可以帮忙吗?

【问题讨论】:

标签: meteor


【解决方案1】:

我知道这是 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();
  }
});

【讨论】:

    【解决方案2】:

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

    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();
    
    });
    

    【讨论】:

    • 这似乎是互联网上唯一的答案。由于我是meteor.js 和node.js 的新手,所以我很难弄清楚该放在哪里... 编辑:我改为在apache vhosts 中处理它。
    • 这是一个服务器代码,所以你把它放在你放任何服务器代码的地方。所以最好在/server 文件夹内,但也可以在if(Meteor.isServer) 条件内的任何位置。
    • 这需要在 DNS 级别完成。参考stackoverflow.com/a/15706411/994922
    【解决方案3】:

    我在客户端使用此代码:

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

    它非常简单且有效。我希望这能回答你的问题。 谢谢

    【讨论】:

      猜你喜欢
      • 2015-11-03
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      • 2016-02-17
      • 1970-01-01
      • 2015-01-28
      • 2010-11-09
      相关资源
      最近更新 更多