本地环境下的Rails子域名配置

13

我想在本地主机上测试子域名。 我有以下说明:在启动服务器来运行应用程序之前,主机应该被配置以便应用程序能够支持多个用户的子域名。 要做到这一点,请在终端中键入sudo nano /etc/hosts,然后将子域名添加到文件末尾,如下所示:

127.0.0.1 admin.daycare.no
127.0.0.1 daycare.no
127.0.0.1 worker.daycare.no
127.0.0.1 manager.daycare.no
127.0.0.1 parent.daycare.no
我按照上述说明进行操作,但在尝试检索URL时遇到了以下错误:http://daycare.no:3000/
Unable to determine IP address from hostname daycare.no
The DNS server returned: Name Error: The domain name does not exist.
This means that the cache was not able to resolve the hostname presented in the URL. 
Check if the address is correct.

请问我该如何解决这个问题?


1
谁添加了关闭标志?下课后来找我。 - Zabba
4个回答

17

保存/etc/hosts文件后,按以下方式运行Rails应用程序

rails s -p 3000 -b daycare.no

在浏览器中

 http://daycare.no:3000

就个人而言,我使用 lvh.me:3000 来运行

rails s -p 3000 -b lvh.me

无需更改/etc/hosts文件。

默认情况下,您无法在没有互联网连接的情况下浏览链接lvh.me:3000,解决方法是将127.0.0.1 lvh.me添加到主机文件中。

# /etc/hosts file
127.0.0.1   localhost
127.0.0.1   lvh.me #make sure lvh.me is after localhost otherwise will not work

但是,每次重新启动服务器都运行这个命令有点烦人。

设置您的自定义命令:

sudo nano .bash_profile
# OR
sudo nano .bashrc
# OR
sudo nano .profile

并添加这些行:

alias lvh='rails s -p 3000 -b lvh.me'
alias lvh_production='RAILS_ENV=production rails s -p 3000 -b lvh.me' #production

不要忘记重新启动终端标签页,关闭并打开新标签页或在同一标签页上运行此命令 . ~/.bash_profile,具体取决于您所使用的方式。


另一种解决方案是使用POW(链接)服务器,可以为您提供自定义域名,例如 daycare.dev


1
之所以需要在IP地址后面加上 ":3000",是因为 "/etc/hosts" 文件只映射IP地址,而不包含端口信息。 - Zabba
为什么我们不能使用 rails s -p 3000 -b 0.0.0.0? - Dinesh Saini
1
@DineshSaini 那么,你如何访问子域名?你的服务器总是会运行的。 - 7urkm3n

4

我使用 www.vcap.me:3000

在 Rails 6 之前,无需进行其他配置。

在 Rails 6 中,您需要将 www.vcap.me 添加到环境配置中:

config.hosts << 'www.vcap.me'

您可以这样使用它:

www.vcap.me:3000
subdomain1.vcap.me:3000
subdomain2.vcap.me:3000
..

1
为了允许对 subdomain.vcap.me 的请求,您还需要在配置中添加类似于 config.hosts << "app.vcap.me" 的内容。 - Hung Om

2

我正在使用Rails 6。您只需要遵循3个步骤,就可以通过您定义的URL访问Rails服务器,而无需提及端口号。

  1. Edit your hosts file. (as you have done already).

    nano /etc/hosts
    

添加您的URL。

   127.0.0.1 admin.daycare.no
   127.0.0.1 daycare.no
   127.0.0.1 worker.daycare.no
   127.0.0.1 manager.daycare.no
   127.0.0.1 parent.daycare.no 
  1. Add all URLs to the environment configuration

    config.hosts << 'admin.daycare.no'
    config.hosts << 'daycare.no'
    config.hosts << 'worker.daycare.no'
    config.hosts << 'manager.daycare.no'
    config.hosts << 'parent.daycare.no'
    
  2. Now just run

     rvmsudo rails s -p80
    
打开你的浏览器,输入网址 http://admin.daycare.no

0

编辑您的hosts文件是一种非常混乱的方式来完成这种事情。问题在于,有些软件不会读取该文件,而是直接转到DNS进行解析。

xip.io这样的服务可以提供帮助。您可以使用类似以下的地址:

http://test.127.0.0.1.xip.io/

这将始终解析为127.0.0.1。

还有一些东西,如Puma dev,它们带有自己的解析器,用于.test域,因此site.test在本地工作时无需编辑任何文件。

这两个系统的优点是您可以添加任意位,它仍然有效:子域名.test.test和子域名.127.0.0.1.xip.io也以相同的方式解析。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接