Can I make Rails / WEBrick recognize entries in /etc/hosts as subdomains (instead of domains)?
Asked Answered
F

1

1

I'm trying to use subdomains locally for a Rails app so I added the following line to my /etc/hosts file:

# add 'test' subdomain for localhost
127.0.0.1 test.localhost

Now I can point my browser to test.localhost:3000 and it hits my Rails app.

However, Rails or WEBrick interprets the whole darn thang as the domain:

# logging in the controller
logger.debug("domain: '#{request.domain}', subdomain: '#{request.subdomain}'")

# output in the console
domain: 'test.localhost', subdomain: ''

Is there an easy way to get WEBrick Rails to interpret test as the subdomain?

Thanks!

Update

I ended up making a before_action as a workaround.

def set_domain_and_subdomain
  @domain = request.domain
  @subdomain = request.subdomain

  # HACK: force /etc/hosts subdomains
  if Rails.env.development?
    if m = request.domain.match(/([^\.]+).localhost/)
      @subdomain = m[1]
      @domain = 'localhost'
    end
  end
end

But I'm still curious if there's a way to do this universally on my computer (i.e. in `/etc/hosts or something)

Faydra answered 19/8, 2014 at 16:54 Comment(1)
I'm aware of services like lvh.me but I don't know how to make it share the same session as localhost so it forces me to facebook auth into the Rails app each time :(Faydra
D
6

Pretty late to find this post, but for posterity: https://github.com/rails/rails/issues/12438

Setting the top level domain length (TLD) allowed request.subdomain to target the subdomain as you'd expect.

I put config.action_dispatch.tld_length = 0 into config/environments/development.rb and everything worked swimmingly.

Remember to restart your server

Diazomethane answered 25/6, 2015 at 22:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.