diff --git a/lib/excon/connection.rb b/lib/excon/connection.rb index a43cf20a..552dece5 100644 --- a/lib/excon/connection.rb +++ b/lib/excon/connection.rb @@ -252,6 +252,12 @@ def request(params={}, &block) datum[:headers]['Host'] ||= datum[:host] + port_string(datum) end + # RFC 7230, section 5.4, states that the Host header SHOULD be the first one # to be present. + # Some web servers will reject the request if it comes too late, so let's hoist it to the top. + if host = datum[:headers].delete('Host') + datum[:headers] = { 'Host' => host }.merge(datum[:headers]) + end + # if path is empty or doesn't start with '/', insert one unless datum[:path][0, 1] == '/' datum[:path] = datum[:path].dup.insert(0, '/') diff --git a/tests/request_headers_tests.rb b/tests/request_headers_tests.rb index 12ebbc7a..ecb66827 100644 --- a/tests/request_headers_tests.rb +++ b/tests/request_headers_tests.rb @@ -16,6 +16,14 @@ end + tests('header order') do + tests('host is the first sent header by default').returns('host: localhost:9292') do + response = Excon.post('http://localhost:9292/') + + response.body.lines.first.chomp + end + end + end end