Reputation: 77
Im new in meteor. It will be cool to automatic redirect from
example.com
to
www.example.com
. Can anyone help?
Upvotes: 3
Views: 939
Reputation: 1280
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
Upvotes: 0
Reputation: 1111
I know this is 2 years old but it doesn't have an accepted answer so I'm providing a complete answer:
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:
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();
}
});
Upvotes: 7
Reputation: 19544
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();
});
Upvotes: 0