做到這一點是寫一個重寫請求頭一個簡單的機架中間件庫的最佳方式以便您的Rails應用獲取您期望的url,但從用戶的角度來看,url不會更改。這樣,您就不必對您的Rails應用程序的任何更改(或路由文件)
例如機架的lib將改寫:users.example.com => example.com/users
這創業板應該做的正是你:http://github.com/jtrupiano/rack-rewrite
的代碼示例
注意更新:這是快速寫入,沒有經過測試的,但應該設置你在正確的道路上。另外,我還沒有檢查出機架重寫的寶石,這可能使這個更簡單
# your rack middleware lib. stick this in you lib dir
class RewriteSubdomainToPath
def initialize(app)
@app = app
end
def call(env)
original_host = env['SERVER_NAME']
subdomain = get_subdomain(original_host)
if subdomain
new_host = get_domain(original_host)
env['PATH_INFO'] = [subdomain, env['PATH_INFO']].join('/')
env['HTTP_X_FORWARDED_HOST'] = [original_host, new_host].join(', ')
logger.info("Reroute: mapped #{original_host} => #{new_host}") if defined?(Rails.logger)
end
@app.call(env)
end
def get_subdomain
# code to find a subdomain. simple regex is probably find, but you might need to handle
# different TLD lengths for example .co.uk
# google this, there are lots of examples
end
def get_domain
# get the domain without the subdomain. same comments as above
end
end
# then in an initializer
Rails.application.config.middleware.use RewriteSubdomainToPath
我爲此添加了100個代表獎金 - 我遇到了類似的困境,所以一個可行的答案會很棒。 – Jeriko 2010-09-20 12:00:46
哪個版本的Rails? 2.x或3? – tommasop 2010-09-24 09:51:54
在我的情況下,2.3,儘管jeriko現在值得更多的關注。 – mark 2010-09-24 10:49:55