Created
October 25, 2010 23:33
-
-
Save kkaefer/646017 to your computer and use it in GitHub Desktop.
node.js proxy to enforce HTTPS and remove cookies
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'); | |
var secure = new RegExp('(' + [ | |
'facebook.com', | |
'twitter.com', | |
'google.com' | |
].join('|').replace('.', '\\.') + ')$'); | |
var noSecure = new RegExp('^(' + [ | |
'http://(www\.)?google\.com/(image|imghp)', | |
'http://(translate|video|maps|scholar)\.google\.com/' | |
].join('|') + ')'); | |
http.createServer(function(request, response) { | |
var isSecure = secure.test(request.headers['host']); | |
if (isSecure && !noSecure.test(request.url)) { | |
response.writeHead(301, { 'Location': 'https' + request.url.substr(request.url.indexOf(':')) }); | |
response.end(); | |
} | |
else { | |
// Cookieless proxy; base from http://www.catonmat.net/http-proxy-in-nodejs | |
if (isSecure && 'cookie' in request.headers) delete request.headers['cookie']; | |
var proxy = http.createClient(80, request.headers['host']); | |
var proxy_request = proxy.request(request.method, request.url, request.headers); | |
proxy_request.on('response', function (proxy_response) { | |
proxy_response.on('data', function(chunk) { | |
response.write(chunk, 'binary'); | |
}); | |
proxy_response.on('end', function() { | |
response.end(); | |
}); | |
if (isSecure && 'set-cookie' in proxy_response.headers) delete proxy_response.headers['set-cookie']; | |
response.writeHead(proxy_response.statusCode, proxy_response.headers); | |
}); | |
request.on('data', function(chunk) { | |
proxy_request.write(chunk, 'binary'); | |
}); | |
request.on('end', function() { | |
proxy_request.end(); | |
}); | |
} | |
}).listen(8080); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that a pac file which only lists the relevant domains/websites is probably a better approach since node.js doesn't do pipelining of HTTP requests.