Created
May 25, 2014 03:30
-
-
Save dstroot/aa9a33b5cf743c087319 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is for SEO: We *only* want to serve from | |
// either www.domain.com or just domain.com but *not* both. | |
// So we need to choose and then do a 301 redirect to get | |
// traffic where we want it. | |
// | |
// NOTE: Don't hardcode the http:// or https:// in the redirect | |
// URI; this makes life suck when switching between dev and prod | |
// environments - use req.protocol instead as we do below. | |
// | |
// Also note that in order to use req.protocol reliably behind a | |
// proxy performing SSL termination (such as Elastic Load Balancer), | |
// you need to make sure that the trust proxy setting is enabled. | |
// This will ensure that req.protocol returns the protocol that | |
// the browser sees, not the protocol that finally made it to | |
// your server. | |
// | |
// Be sure to use req.headers.host instead of req.host, as the | |
// latter strips out the port number. So, if you were to handle | |
// a request for www.example.com:3000, you'd redirect the user | |
// to www.example.com, minus the correct port number. | |
// app.all('/*', function (req, res, next) { | |
// if (req.headers.host.match(/^www\./) !== null ) { | |
// // 301 is a "Moved Permanently" redirect. | |
// res.redirect(301, req.protocol + '://' + req.headers.host.replace(/^www\./, '') + req.url); | |
// } else { | |
// next(); | |
// } | |
// }); | |
function wwwRedirect (req, res, next) { | |
if (req.headers.host.slice(0, 4) === 'www.') { | |
var newHost = req.headers.host.slice(4); | |
// 301 is a "Moved Permanently" redirect. | |
return res.redirect(301, req.protocol + '://' + newHost + req.originalUrl); | |
} | |
next(); | |
} | |
app.use(wwwRedirect); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment