如何从URL获取子域值?

如何在rails中获取子域值,是否有内置的方法来执行此操作?

例如

test123.example.com 

我想要url的test123部分。

Rails 3.0内置了此function,您可以从request.subdomain访问子域。

您还可以根据子域进行路由:

 class SupportSubdomain def self.matches?(request) request.subdomain == "support" end end Basecamp::Application.routes do constraints(SupportSubdomain) do match "/foo/bar", :to => "foo#bar" end end 

如果您使用的是2.3,则需要使用subdomain-fu等插件。

在控制器中使用以下方法

 request.subdomains 

返回子域数组

account_location也是一个很好的插件。 使用后,您可以根据不同的子域找到该帐户。 你可以通过写作从url中找到子域名

 request.subdomains(0).first 

在你的代码中。

如果您正在使用字符串,并假设它可以是一个真正的URI,您可以这样做以提取子域。

 require 'uri' uri = URI.parse('http://test123.example.com') uri.host.split('.').first => "test123" 

https://stackoverflow.com/a/13243810/3407381

在控制器中简单,只需执行以下操作即可

 unless request.subdomains.any? #No domains available redirect redirect_to subdomain: 'www' end 

您可以使用SubdomainFu插件 。 这个插件为您提供了一个方法current_subdomain,它返回您应用的current_subdomain。

你也可以看看这个Railscast

UPDATE

您还可以使用request.subdomains这将为您提供一系列子域名。

对于希望使用WEBrick在localhost上获取子域的任何人:

config.action_dispatch.tld_length = 0放入config/environments/development.rb ,一切都应该有效。

链接到SO发布在这里: 我可以让Rails / WEBrick将/ etc / hosts中的条目识别为子域(而不是域)吗?

链接到Githubpost: https : //github.com/rails/rails/issues/12438

派对有点晚了,但这是我在旧版本的rails中使用的。

subdomain = rquest.subdomains.join('.')

它应该在较新版本中向后兼容