Skip to content

Instantly share code, notes, and snippets.

@aJanuary
Created January 24, 2012 09:50
Show Gist options
  • Save aJanuary/1669327 to your computer and use it in GitHub Desktop.
Save aJanuary/1669327 to your computer and use it in GitHub Desktop.
Redirect Proxy
#!/usr/bin/ruby
require 'webrick/httpproxy'
require 'optparse'
# Monkey patch HTTPRequest so we can modify the url and cookie
class WEBrick::HTTPRequest
def update_uri(uri)
@unparsed_uri = uri
@request_uri = parse_uri(uri)
end
def set_cookie(cookie)
@header['cookie'] = [cookie]
end
end
def redirect_request(req, res)
if @options[:from] == req.request_uri.to_s
puts "Redirecting from #{@options[:from]} to #{@options[:to]}"
puts @options[:cookie]
req.set_cookie(@options[:cookie]) if @options[:cookie]
req.update_uri(@options[:to])
end
end
@options = {}
optparse = OptionParser.new do |opts|
opts.banner = 'Usage: redirect_proxy.rb [options] from to'
@options[:cookie] = nil
opts.on('-c', '--cookie COOKIE', 'Set cookie when redirecting requests') do |cookie|
@options[:cookie] = cookie
end
@options[:forwardproxy] = nil
opts.on('-f', '--forwardproxy PROXY', 'Pass requests through a proxy') do |proxy|
@options[:proxy] = URI::parse(proxy)
end
@options[:port] = 9999
opts.on('-p', '--port PORT', 'Port to host the proxy on') do |port|
@options[:port] = port
end
opts.on('-h', '--help', 'Displays this screen') do
puts opts
exit
end
end
begin
optparse.parse!
rescue
puts optparse
exit(-1)
end
if ARGV.length < 2
puts optparse
exit(-1)
end
@options[:from] = ARGV[0]
@options[:to] = ARGV[1]
server = WEBrick::HTTPProxyServer.new :Port=> @options[:port],
:ProxyVia => @options[:forwardproxy],
:ProxyURI => @options[:forwardproxy],
:RequestCallback => method(:redirect_request)
trap "INT" do server.shutdown end
server.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment