, proxy chains and HTTP_X_FORWARDED_HOST


We've an application that uses url_for in controllers and views. In views, url_for generates a relative url (as if :only_path where used). All is fine there.

However, in controllers, url_for generates a full url, with the host name. This causes problems when we have a chain of Apache proxy servers:

My Browser ---> Proxy 1 ----> Proxy 2 ----> Phusion Deployment Server.

In this scenario, the request header item HTTP_X_FORWARDED_HOST contains the following:

proxy1:81, proxy2

Rails extracts the host by splitting this string and getting the last item:

(actionpack-2.3.2\lib\action_controller\request.rb line 271)

    def raw_host_with_port       if forwarded = env["HTTP_X_FORWARDED_HOST"]         forwarded.split(/,\s?/).last       else         env['HTTP_HOST'] || "#{env['SERVER_NAME'] || env ['SERVER_ADDR']}:#{env['SERVER_PORT']}"       end     end

What happens is that we get proxy2 as the host.

Shouldn't it be trying to get the first item instead -


giving us proxy1:81 instead?

Is this a bug? If not, is there reasoning behind this?


Actually, I've just seen the following in the Django mailing lists:

Looks like the option to select the last item is deliberate.