diff --git a/lib/rack/reverse_proxy.rb b/lib/rack/reverse_proxy.rb index 4d3de34..e33968c 100644 --- a/lib/rack/reverse_proxy.rb +++ b/lib/rack/reverse_proxy.rb @@ -46,7 +46,11 @@ def proxy(env, source_request, matcher) target_request_headers = extract_http_request_headers(source_request.env) if options[:preserve_host] - target_request_headers['HOST'] = "#{uri.host}:#{uri.port}" + if uri.port == uri.default_port + target_request_headers['HOST'] = uri.host + else + target_request_headers['HOST'] = "#{uri.host}:#{uri.port}" + end end if options[:x_forwarded_host] diff --git a/spec/rack/reverse_proxy_spec.rb b/spec/rack/reverse_proxy_spec.rb index ea35a55..53ed50a 100644 --- a/spec/rack/reverse_proxy_spec.rb +++ b/spec/rack/reverse_proxy_spec.rb @@ -37,10 +37,10 @@ def app last_response.body.should == "Proxied App2" end - it "should set the Host header" do + it "should set the Host header w/o default port" do stub_request(:any, 'example.com/test/stuff') get '/test/stuff' - a_request(:get, 'http://example.com/test/stuff').with(:headers => {"Host" => "example.com:80"}).should have_been_made + a_request(:get, 'http://example.com/test/stuff').with(:headers => {"Host" => "example.com"}).should have_been_made end it "should set the X-Forwarded-Host header to the proxying host by default" do @@ -49,6 +49,20 @@ def app a_request(:get, 'http://example.com/test/stuff').with(:headers => {'X-Forwarded-Host' => 'example.org'}).should have_been_made end + describe "with non-default port" do + def app + Rack::ReverseProxy.new(dummy_app) do + reverse_proxy '/test', 'http://example.com:8080/' + end + end + + it "should set the Host header including non-default port" do + stub_request(:any, 'example.com:8080/test/stuff') + get '/test/stuff' + a_request(:get, 'http://example.com:8080/test/stuff').with(:headers => {"Host" => "example.com:8080"}).should have_been_made + end + end + describe "with preserve host turned off" do def app Rack::ReverseProxy.new(dummy_app) do @@ -166,6 +180,25 @@ def app last_response.body.should == "Proxied Secure App" end + it "should set the Host header w/o default port" do + stub_request(:any, 'https://example.com/test/stuff') + get '/test/stuff' + a_request(:get, 'https://example.com/test/stuff').with(:headers => {"Host" => "example.com"}).should have_been_made + end + end + + describe "with a https route on non-default port" do + def app + Rack::ReverseProxy.new(dummy_app) do + reverse_proxy '/test', 'https://example.com:8443' + end + end + + it "should set the Host header including non-default port" do + stub_request(:any, 'https://example.com:8443/test/stuff') + get '/test/stuff' + a_request(:get, 'https://example.com:8443/test/stuff').with(:headers => {"Host" => "example.com:8443"}).should have_been_made + end end describe "with a route as a string" do