how can I get the subdomain value in rails, is there a built-in way to do this?
e.g.
test123.example.com
I want the test123 part of the url.
You can do this by first getting the domain name (e.g. sub.example.com => example.co.uk) and then use strstr to get the subdomains. This seems the best solution as it also allows for domains without a subdomain, rather than retruning the domain name as the subdomain being the part before the first dot.
Each domain name can have up to 500 subdomains. You can also add multiple levels of subdomains, such as info.blog.yoursite.com. A subdomain can be up to 255 characters long, but if you have multiple levels in your subdomain, each level can only be 63 characters long.
It can be used like this: Route::group(array('domain' => '{subdomain}. project. dev'), function() { Route::get('foo', function($subdomain) { // Here I can access $subdomain }); $subdomain = Route::input('subdomain'); });
Rails 3.0 has this capability built-in, you can access the subdomain from request.subdomain
.
You can also route based on the 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
If you're using 2.3, you'll need to use a plugin such as subdomain-fu.
Use the following method inside your controller
request.subdomains
This Returns an array of subdomains
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With