LoginSignup
3
1

More than 5 years have passed since last update.

Rails の subdomain の TLD 長の罠

Last updated at Posted at 2016-12-06

Rails で subdomain を扱うときにハマりがちなのは、TLD の長さによって subdomain の値が異なることです。

例えば foo.example.com というドメインから、 foo.example.co.jp にドメインを変更すると、今まで動いていた subdomain 関連のコードがうまく動かなくなりがちです。

ソースを見てみましょう。(ActionPack 5.0.1)

      # Returns all the \subdomains as an array, so <tt>["dev", "www"]</tt> would be
      # returned for "dev.www.rubyonrails.org". You can specify a different <tt>tld_length</tt>,
      # such as 2 to catch <tt>["www"]</tt> instead of <tt>["www", "rubyonrails"]</tt>
      # in "www.rubyonrails.co.uk".
      def subdomains(tld_length = @@tld_length)
        ActionDispatch::Http::URL.extract_subdomains(host, tld_length)
      end

      # Returns all the \subdomains as a string, so <tt>"dev.www"</tt> would be
      # returned for "dev.www.rubyonrails.org". You can specify a different <tt>tld_length</tt>,
      # such as 2 to catch <tt>"www"</tt> instead of <tt>"www.rubyonrails"</tt>
      # in "www.rubyonrails.co.uk".
      def subdomain(tld_length = @@tld_length)
        ActionDispatch::Http::URL.extract_subdomain(host, tld_length)
      end

この tld_length によって挙動が変わってくるので、ドメイン変更時 tld_length を適切に変えるか、request.subdomain は使わず、request.subdomains.first の値を使うなどの考慮をしていないと、突然意図しない挙動になってハマりがちなので注意しましょう。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1