问题
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)
回答1:
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
来源:https://stackoverflow.com/questions/25388948/can-i-make-rails-webrick-recognize-entries-in-etc-hosts-as-subdomains-instea