原文出自:[url]http://gravityblast.com/2009/08/15/hostname-middleware-for-rails-apps-on-multiple-servers/[/url]
如果你的Rails工程是运行在多服务器上,并且有负载均衡的话。那么,你的每次请求就是来自不同的主机。如果,你希望能够把到底是那个服务器的主机在处理你的请求,那么你可以用下面的script把主机名显示到请求也页面的标题上。
lib/hostname.rb:
另:注意修改environment.rb,添加:
如果你的Rails工程是运行在多服务器上,并且有负载均衡的话。那么,你的每次请求就是来自不同的主机。如果,你希望能够把到底是那个服务器的主机在处理你的请求,那么你可以用下面的script把主机名显示到请求也页面的标题上。
lib/hostname.rb:
class Hostname
TITLE_REGEXP = /(<title>)([^<]*)(<\/title>)/i
def initialize(app, hostname="")
@app = app
@title_suffix = " - on #{hostname}"
end
def call(env)
status, headers, response = @app.call(env)
add_hostname(response, headers) if headers["Content-Type"] =~ %r{text/html}
[status, headers, response]
end
def add_hostname(response, headers)
response.each{|s| s.sub!(TITLE_REGEXP, "\\1\\2#{@title_suffix}\\3") if s =~ TITLE_REGEXP}
headers["Content-Length"] = (headers["Content-Length"].to_i + @title_suffix.length).to_s
nil
end
end
另:注意修改environment.rb,添加:
config.middleware.use "Hostname", %x"hostname".chomp