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
の値を使うなどの考慮をしていないと、突然意図しない挙動になってハマりがちなので注意しましょう。