-
-
Save thepatrick/7485043 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
var http = require('http'); | |
http.createServer(function(req, res){ | |
function giveup(code) { | |
if(code == 410) { | |
res.writeHead(410, { | |
Server: "pfe+redirect", | |
"X-Patrick-Says": "Redirect Engine in just 41 lines of code. node.js rocks" | |
}); | |
res.end("This content is gone, there is no forwarding address. Sorry."); | |
} else { | |
res.writeHead(302, { | |
Location: "http://thepatrick.com.au/", | |
Server: "pfe/redirect", | |
"X-Patrick-Says": "Redirect Engine in just 41 lines of code. node.js rocks" | |
}); | |
res.end("Redirecting to http://thepatrick.com.au/"); | |
} | |
} | |
function re(url, m, destUrl, status) { | |
if(_ref = url.match(new RegExp(m))) { | |
if(status == 410) { | |
giveup(410); | |
} else { | |
for(var idx = 1; idx < _ref.length; idx++) { | |
destUrl = destUrl.replace("$" + idx, _ref[idx]); | |
} | |
res.writeHead(status || 302, { | |
Location: destUrl, | |
Server: "pfe/redirect", | |
"X-Patrick-Says": "Redirect Engine in just 41 lines of code. node.js rocks" | |
}); | |
res.end(); | |
} | |
return true; | |
} | |
return false; | |
} | |
// frontendserver rewrites URLs like "http://soapbox.co.nz/somewhere" to "http://127.0.0.1:10394/soapbox/somewhere" | |
if(req.url.substring(0, 15) == "/patrickgeeknz/") { | |
patrickgeeknz(re.bind(null, req.url.substring(15)), giveup); | |
} else if(req.url.substring(0, 9) == "/soapbox/") { | |
soapbox(re.bind(null, req.url.substring(9)), function() { | |
patrickgeeknz(re.bind(null, req.url.substring(9)), giveup); | |
}); | |
} else { | |
giveup(); | |
} | |
}).listen(10394, function() { | |
console.log("Up and running on http://localhost:10394/ ..."); | |
}); | |
function soapbox(re, giveup) { | |
// Either 301 (permanent) and 302 (temporary) HTTP status codes are supported | |
re("^bar", "http://www.google.com/", 302) || | |
re("^bam", "http://www.google.com/", 301) || | |
// Simple substituion is supported | |
re("^past/([0-9]{4})/([0-9]{1,2})[/]?([0-9]{1,2})?[/]?$", "http://myio.com.au/archive/$1/$2/", 301) || | |
// 410 (and no forwarding URL, obviously) and it'll send a 410 gone instead | |
re("^gone", null, 410) || | |
// If none of our rules match we giveup(), | |
// which in this case tries the patrickgeeknz() set below | |
giveup(); | |
} | |
function patrickgeeknz(re, giveup) { | |
// Send the default thing away | |
re("^$", "http://thepatrick.com.au/", 301) || | |
giveup(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment