Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Per proxy additional header functionality #40

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.rdoc
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ Below is an example for configuring the middleware:
# Forward the path /test* to http://example.com/test*
reverse_proxy '/test', 'http://example.com/'

# Forward the path /test* to http://example.com/test* with headers
reverse_proxy '/test', 'http://example.com/' do
add_header 'content-type', 'application/json'
add_header 'x-foo-bar', '12345'
end

# Forward the path /foo/* to http://example.com/bar/*
reverse_proxy /^\/foo(\/.*)$/, 'http://example.com/bar$1', :username => 'name', :password => 'basic_auth_secret'
end
Expand Down
18 changes: 14 additions & 4 deletions lib/rack/reverse_proxy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ def initialize(app = nil, &b)
@app = app || lambda {|env| [404, [], []] }
@matchers = []
@global_options = {:preserve_host => true, :x_forwarded_host => true, :matching => :all, :verify_ssl => true}
@headers = {}
instance_eval &b if block_given?
end

def call(env)
rackreq = Rack::Request.new(env)
matcher = get_matcher rackreq.fullpath
Expand All @@ -18,11 +19,15 @@ def call(env)
uri = matcher.get_uri(rackreq.fullpath,env)
all_opts = @global_options.dup.merge(matcher.options)
headers = Rack::Utils::HeaderHash.new
env.each { |key, value|

env.each do |key, value|
if key =~ /HTTP_(.*)/
headers[$1] = value
end
}
end

@headers.each { |key,value| headers[key] = value }

headers['HOST'] = uri.host if all_opts[:preserve_host]
headers['X-Forwarded-Host'] = rackreq.host if all_opts[:x_forwarded_host]

Expand Down Expand Up @@ -102,10 +107,15 @@ def reverse_proxy_options(options)
@global_options=options
end

def reverse_proxy matcher, url, opts={}
def reverse_proxy matcher, url, opts={}, &block
block.yield if block_given?
raise GenericProxyURI.new(url) if matcher.is_a?(String) && url.is_a?(String) && URI(url).class == URI::Generic
@matchers << ReverseProxyMatcher.new(matcher,url,opts)
end

def add_header name, value
@headers[name.to_s] = value.to_s
end
end

class GenericProxyURI < Exception
Expand Down