Kevin Sylvestre
Kevin Sylvestre

Reputation: 38062

Rails Subdomain in Host Being Replaced

Given the following config/routes.rb:

constraints subdomain: 'subdomain' do
  get 'path', to: 'main#index', as: :sample
end

The following works:

Rails.application.routes.url_helpers.sample_url(host: "a.b")
# "http://subdomain.a.b/path"

The following fails:

Rails.application.routes.url_helpers.sample_url(host: "a.b.c")
# "http://subdomain.b.c/path"

Any way to fix it so subdomains don't replace existing subdomains in the host but instead are linked (i.e. http://subdomain.a.b.c/path)? I realize I can change the subdomain in the route to be subdomain.a - but that'd be a bit of a pain to maintain for multiple subdomains / deployments.

Upvotes: 1

Views: 826

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

Looks like you need to examine tld_length:

:tld_length - Number of labels the TLD id composed of, only used if :subdomain or :domain are supplied. Defaults to ActionDispatch::Http::URL.tld_length, which in turn defaults to 1.

I'll test the specifics, but the issue looks like Rails is only allowing a tld (top level domain) length of 1, which means that you can only have a subdomain and 1 "other" element (subdomain.b.c / subdomain.a.b).

The fix should be to expand the tld_length, which according to this answer, can be done in the config settings /config/application.rb:

# config/application.rb
config.action_dispatch.tld_length = 2

Tests

Without tld_length:

c:\Dev\Apps\torches>rails c
Loading development environment (Rails 5.0.0.1)
irb(main):001:0> Rails.application.routes.url_helpers.sample_url(host: "a.b")
=> "http://subdomain.a.b/path"
irb(main):002:0> Rails.application.routes.url_helpers.sample_url(host: "a.b.c")
=> "http://subdomain.b.c/path"
irb(main):003:0>

With tld_length:

c:\Dev\Apps\torches>rails c
Loading development environment (Rails 5.0.0.1)
irb(main):001:0> Rails.application.routes.url_helpers.sample_url(host: "a.b")
=> "http://subdomain.a.b/path"
irb(main):002:0> Rails.application.routes.url_helpers.sample_url(host: "a.b.c")
=> "http://subdomain.a.b.c/path"
irb(main):003:0>

Upvotes: 1

Benjamin Bouchet
Benjamin Bouchet

Reputation: 13181

create config/initializers/host_name.rb file, where you can place a constant :

HOST_NAME = 'b.c'

then anywhere in your code :

Rails.application.routes.url_helpers.sample_url(host: HOST_NAME, subdomain: 'subdomain.a')

you can also create constants for your subdomains if you like

Upvotes: 0

Related Questions