如何在meteor.js应用程序中从非www重定向到www

use*_*229 3 meteor

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

example.com

www.example.com

.有人可以帮忙吗?

aar*_*son 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();
  }
});
Run Code Online (Sandbox Code Playgroud)

您可以使用以下代码向相反方向(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();
  }
});
Run Code Online (Sandbox Code Playgroud)