Skip to content

Instantly share code, notes, and snippets.

@ismyrnow
Last active December 17, 2015 19:15
Show Gist options
  • Save ismyrnow/8693f32985560b3a26e6 to your computer and use it in GitHub Desktop.
Save ismyrnow/8693f32985560b3a26e6 to your computer and use it in GitHub Desktop.
Node web server redirecting all requests

A Node.js web server, with zero dependencies, which redirects all requests to a URL provided at runtime.

Useful for redirecting Elastic Beanstalk apps to a new location. Just deploy this as a new version, then set the REDIRECT variable.

Run with node server http://google.com or set REDIRECT=http://google.com && node server

var http = require('http');
var port = process.env.PORT || 3000;
var redirectUrl = process.env.REDIRECT || getArg(2);
if (!redirectUrl) {
console.error('No redirect URL setup. ' +
'Please specify a command line argument or "REDIRECT" variable.');
process.exit(1);
}
var server = http.createServer(function(req, res) {
res.writeHead(302, {
'Location': redirectUrl
});
res.end();
});
server.listen(port, function () {
console.log('Web server running on port %s and redirecting to %s',
port, redirectUrl);
});
function getArg(index) {
if (process && process.argv && process.argv.length >= index -1) {
return process.argv[index];
} else {
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment