首页 文章

我可以使用/ etc / hosts文件配置别名[关闭]

提问于
浏览
165

/etc/hosts 文件可用于覆盖dns定义,即将主机名指向不同的ip .

我想使用 /etc/hosts 制作别名记录,即让我的电脑认为www.mysite.com没有指向"hard coded" ip,而是mychangingip.myip.com的同义词 .

可以吗?

9 回答

  • 12

    这可以通过运行本地DNS解析器(类似于dnsmasq)来完成 . 检查https://serverfault.com/questions/22419/set-dns-server-on-os-x-even-when-without-internet-connection

  • 12

    /etc/hosts 不能(通过它自己)生成主机名"aliases" .

    hosts文件从DNS生成内部等效的 APTR 记录,即将主机名映射到IP地址,反之亦然 .

    虽然您可以为特定IP添加多个名称,但这需要您事先知道IP . 它不能用于产生与 CNAME 记录相同的效果,其中名称指向另一个名称,该名称又转换为所需的IP .

  • 153

    如果要通过SSH连接到服务器(具有动态更改的DNS条目),则可以通过(在文件〜/ .ssh / config中)创建条目来有效地添加“别名”:

    Host myAlias
        HostName mychangingip.myip.com
    

    然后你可以“ssh myAlias”(还有其他可能有用的指令,例如用户,端口等) .

  • -2

    我有同样的问题,我通过在我的mac上安装和使用nginx解决了它 . 你没有't need a dns server to do this. You can just take advantage of nginx' s proxy_pass 选项来获得与cname相同的效果 .

    一旦安装了nginx并进行了设置,就可以像这样为 first.com 设置 first.com . 在你的/ etc / hosts中将 first.com 流量转发到127.0.0.1 .

    127.0.0.1 first.com
    

    然后在你的nginx配置上添加以下内容:

    server {
      listen   80;
      server_name  first.com;
      access_log off;
      location / {
          proxy_pass http://second.com;
          proxy_set_header    Host            $host;
          proxy_set_header    X-Real-IP       $remote_addr;
          proxy_set_header    X-Forwarded-for $remote_addr;
          proxy_connect_timeout 300;
      }
    }
    

    这应该有效地为您提供类似cname的设置 . 希望有所帮助!

  • 2

    如果您只需要在hosts文件中拥有最新的IP并且不喜欢自定义DNS设置的开销,那么这个shell脚本可能会为您提供帮助 . 例如,您可以将其作为cronjob定期运行 .

    #!/bin/bash
    # Get the dynamic IP (dirty, I know)
    IP=`host -t a mychangingip.myip.com | perl -nle '/((?:\d+\.?){4})/ && print $1' | head -n1`
    
    # Update the hosts file
    if test -n "$IP"; then
        grep -v www.thesite.com /etc/hosts > /tmp/hosts
        echo "$IP www.thesite.com" >> /tmp/hosts
        cp /tmp/hosts /etc/hosts
    fi
    
  • 38

    我最近调查了这个,我找不到真正的解决方案 . 但是,您可以通过向/etc/resolv.conf添加搜索行来获得您想要的部分内容,例如:

    search myip.com

    然后在尝试解析mychangingip时会查找mychangingip.myip.com另请参阅resolv.conf的手册页

  • 144

    需要注意的是,如果您有这样的条目:

    127.0.0.1     dev.example.com
    

    当你在你的应用程序中实际获得请求时(在我的情况下是ASP.NET),它将逐渐解决为'localhost',所以你不能做这样的事情:

    if (Request.Url.Authority == "dev.example.com) {
       // ...
    }
    

    别名被解析为'localhost' . 我认为这种行为就好像它是一个CNAME

  • 15

    有些服务提供商会为您提供舒适可靠的服务 . 一个突出的例子是dyndns .

  • 1

    我不这么认为,hosts文件实际上不是dns服务器的替代品 . 您可能希望尝试基于文件的SheerDNS,而不是试图弄清楚如何安装和配置绑定DNS . http://threading.2038bug.com/sheerdns/(通过freshmeat找到的最好的轻量级dns服务器) .

相关问题