我可以让 Rails/WEBrick 将/etc/hosts 中的条目识别为子域(而不是域)吗? [英] Can I make Rails / WEBrick recognize entries in /etc/hosts as subdomains (instead of domains)?

查看:28
本文介绍了我可以让 Rails/WEBrick 将/etc/hosts 中的条目识别为子域(而不是域)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在本地为 Rails 应用程序使用子域,因此我将以下行添加到我的 /etc/hosts 文件中:

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

现在我可以将浏览器指向 test.localhost:3000 并且它会访问我的 Rails 应用程序.

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

然而,Rails 或 WEBrick 将整个 darn thang 解释为域:

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: ''

是否有一种简单的方法可以让 WEBrick Rails 将 test 解释为子域?

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

谢谢!

我最终制作了一个 before_action 作为解决方法.

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

但是我仍然很好奇是否有一种方法可以在我的计算机上普遍执行此操作(即在`/etc/hosts 或其他内容中)

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

推荐答案

很晚才找到这个帖子,但为了后代:https://github.com/rails/rails/issues/12438

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

设置顶级域长度 (TLD) 允许 request.subdomain 如您所愿地定位子域.

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

我将 config.action_dispatch.tld_length = 0 放入 config/environments/development.rb 并且一切顺利.

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

记得重启服务器

这篇关于我可以让 Rails/WEBrick 将/etc/hosts 中的条目识别为子域(而不是域)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆