5

我有一个 Rails 应用程序服务器正在侦听端口 9000,并通过 haproxy 调用。我从该服务器发出的所有重定向都通过端口 9000 重定向回来,而它们应该在端口 80 上发送回来。

我正在使用 haproxy + nginx + 乘客的组合。有没有办法确保所有重定向都通过端口 80 发送,而不管实际服务器正在侦听的端口是什么?

我不在乎它是否改变了 haproxy、nginx、Passenger 或 Rails。除非另有说明,否则我只需要确保大多数请求都被发送回端口 80。

谢谢!

4

4 回答 4

12

就像 elektronaut 指出的那样,这可能应该在您的代理配置中处理。也就是说,ActiveSupport::UrlFor#url_for 有一些可能有用的信息。看看http://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/routing/url_for.rb

我认为归结为将两个参数传递给您的 url_for 和/或 link_to 调用。第一个是:port => 123参数,第二个是:only_path => false生成完整的链接,包括域、端口等。

因此,在生成链接时,您可能会这样做:

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

在创建自定义 url 时,您可能会这样做:

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

对于重定向:

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

我希望这会有所帮助,如果没有,您能否更具体地说明如何生成 URL、rails 为您生成什么以及您希望它生成什么。

更新: 我不知道这一点,但您似乎可以为使用 url_for 生成的 URL 的 rails 设置默认值,其他所有生成链接和/或 URL 的东西都会使用它。这里有一篇很好的文章:http: //lucastej.blogspot.com/2008/01/ruby-on-rails-how-to-set-urlfor.html

或者给你总结一下:

将此添加到您的application_controler.rb

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

和这个:

helper_method :url_for

第一个块在控制器中设置默认值,第二个块使 url_for 助手使用在控制器中找到的那个,因此默认值也适用于它。

于 2010-06-19T08:17:18.670 回答
2

重写重定向可能应该是 Web 服务器的责任,但您可以破解请求对象以始终在 before_filter 中返回端口 80:

class ApplicationController < ActionController::Base
    before_filter :use_port_80 if RAILS_ENV == production
    def use_port_80
        class << request
            def port; 80; end
        end
    end
end
于 2010-06-14T23:16:40.183 回答
1

我建议应该通过将此代码添加到配置中来修复它。

rsprep (.*):9000(.*) \1\2
于 2010-06-19T09:55:11.813 回答
0

如果这是链接到与站点所在站点相同的服务器的链接。您可以使用相对链接而不是绝对链接。如果您使用辅助方法来创建链接,您可以使用_path后缀而不是_url.

如果你routes.rb看起来像这样:

ActionController::Routing::Routes.draw do |map|
  map.resources :users
end

或在轨道 3 中:

YourAppName::Application.routes.draw do
  resources :users
end

您可以使用以下辅助方法来创建相对链接:

users_path     #=> /users
user_path      #=> /users/:id
edit_user_path #=> /users/:id/edit
new_user_path  #=> /users/new

# instead of

users_url      #=> http(s)://example.com:9000/users
user_url       #=> http(s)://example.com:9000/users/:id
edit_user_url  #=> http(s)://example.com:9000/users/:id/edit
new_user_url   #=> http(s)://example.com:9000/users/new

如您所见,这些链接独立于您正在运行的端口或主机。

于 2010-06-17T13:42:29.263 回答