[英]How to redirect from non www to www in meteor.js app
Im new in meteor. 我是流星的新手。 It will be cool to automatic redirect from
自动重定向会很酷
example.com
example.com
to 至
www.example.com
www.example.com
. 。 Can anyone help?
有人可以帮忙吗?
I know this is 2 years old but it doesn't have an accepted answer so I'm providing a complete answer: 我知道这是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();
}
});
You can go the opposite direction (www to non-www) with the following code: 您可以使用以下代码向相反方向(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();
}
});
You can do this with adding a piece of middleware. 您可以通过添加一个中间件来完成此操作。 This should get you started:
这应该让你开始:
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();
});
I am use with this code On CLIENT SIDE: 我在客户端使用此代码:
Meteor.startup(function () {
if (location.host.indexOf('www.domain.com') !== 0) {
location = 'www.domain.com';
}
});
Its verry simple and work. 它的简单和工作。 I hope this answer your questions.
我希望这能回答你的问题。 Thanks
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.