Search code examples
ruby-on-railsnginxpassengerhaproxy

Send Redirects To Specific Ports


I have an Rails application server that is listening on port 9000, and is being called through haproxy. All my redirects from that server are being redirected back through port 9000, when they should be sent back on port 80.

I am using a combination of haproxy + nginx + passenger. Is there a way to make sure all redirects are being sent through port 80, regardless of what port the actual server is listening on?

I don't care if its a haproxy, nginx, Passenger, or Rails change. I just need to make sure most requests unless specified otherwise, are sent back to port 80.

Thanks!


Solution

  • Like elektronaut indicated, this is probably something that should be handled in your proxy's configuration. That said, ActiveSupport::UrlFor#url_for has some information that might be useful. Take a look at http://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/routing/url_for.rb

    What I think it boils down to is passing two arguments into your url_for and/or link_to calls. First is the :port => 123 argument, the second is :only_path => false so that it generates the full link including domain, port, etc.

    So when generating a link, you might do:

    link_to 'test', root_url(:port => 80, :only_path => false)
    

    and when creating a custom url you might do:

    url_for :controller => 'test', :action => 'index', :port => 80, :only_path => false
    

    For a redirect:

    redirect_to root_url(:port => 80, :only_path => false)
    

    I hope this helps, and if it doesn't, can you be more specific about how you generating your URLs, what rails is generating for you, and what you would like it to generate.

    Update: I wasn't aware of this, but it seems you can set defaults for the URL's rails generates with url_for, which is used by everything else that generates links and/or URLs. There is a good write up about it here: http://lucastej.blogspot.com/2008/01/ruby-on-rails-how-to-set-urlfor.html

    Or to sum it up for you:

    Add this to your application_controler.rb

    def default_url_options(options)
       { :only_path => false, :port => 80 }
    end
    

    and this:

    helper_method :url_for
    

    The first block sets defaults in the controllers, the second causes the url_for helper to use the one found in the controllers, so the defaults apply to that as well.