diff --git a/README.rdoc b/README.rdoc index be1f0ad..e279ba8 100644 --- a/README.rdoc +++ b/README.rdoc @@ -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 diff --git a/lib/rack/reverse_proxy.rb b/lib/rack/reverse_proxy.rb index ddadd3f..300c6b8 100644 --- a/lib/rack/reverse_proxy.rb +++ b/lib/rack/reverse_proxy.rb @@ -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 @@ -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] @@ -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