[英]Ruby on Rails route for wildcard subdomains to a controller/action
我動態創建username.users.example.com
形式的URL:
bob.users.example.com
tim.users.example.com
scott.users.example.com
所有*.users.example.com
請求都應該轉到特定的控制器/操作。 如何在routes.rb
指定它?
對www.example.com
所有其他請求都會轉到routes.rb
文件中的正常路由列表。
更新 :我觀看有關子域的railscast ,它顯示了下面的代碼,這似乎正是我需要的(更改控制器和子域):
match '', to: 'my_controller#show', constraints: {subdomain: /.+\.users/}
問題是它只匹配根URL。 我需要這個以匹配每個可能的URL與*.users
子域。 顯然我會把它放在我的routes.rb
文件的頂部。 但是,我如何指定一個包羅萬象的路線? 它只是'*'
嗎? 或'/*'
?
我想,你只需要做以下事情:
在lib
創建一個類Subdomain
:
class Subdomain
def self.matches?(request)
request.subdomain.present? && request.host.include?('.users')
end
end
在你的routes
:
constraints Subdomain do
match '', to: 'my_controller#show'
end
您可以通過創建matches?
根據某些特定條件動態約束路由matches?
方法
讓我們說我們必須過濾URL的子域
constraints Subdomain do
get '*path', to: 'users#show'
end
class Subdomain
def self.matches?(request)
(request.subdomain.present? && request.subdomain.start_with?('.users')
end
end
我們在這里做的是檢查URL,如果它從子域users
開始,然后只點擊users#show
action。 你的班級必須有mathes?
方法或類方法或實例方法。 如果你想讓它成為一個實例方法,那么就做
constraints Subdomain.new do
get '*path', to: 'proxy#index'
end
你可以使用lambda
同樣的東西,如下所示。
我們也可以使用lambdas
而不是編寫類
get '*path', to: 'users#show', constraints: lambda{|request|request.env['SERVER_NAME'].match('.users')}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.