How to get the subdomain value from a url?

后端 未结 9 2258
太阳男子
太阳男子 2020-12-09 02:15

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

相关标签:
9条回答
  • 2020-12-09 02:50

    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.

    0 讨论(0)
  • 2020-12-09 02:52

    Use the following method inside your controller

    request.subdomains
    

    This Returns an array of subdomains

    0 讨论(0)
  • 2020-12-09 02:52

    In case you are working with a string, and assuming it can be a true URI, you can do this to extract the subdomain.

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

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

    0 讨论(0)
  • 2020-12-09 03:00

    You can use the SubdomainFu plugin. This plugin gives you a method current_subdomain which returns the current_subdomain of your app.

    You can also have a look at this Railscast

    UPDATE

    You can also use request.subdomains this will give you an array of subdomains.

    0 讨论(0)
  • 2020-12-09 03:02

    A bit late to the party but here's what I used in older versions of rails.

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

    It should be backwards compatible in newer versions

    0 讨论(0)
  • 2020-12-09 03:03

    account_location is also a good plugin. After using it, you can find the account based on different subdomains. And you can find out subdomain from url just by writing

    request.subdomains(0).first
    in your code.

    0 讨论(0)
提交回复
热议问题