5

If I want to add an entry to /etc/hosts to resolve all traffic for example.com to 1.2.3.4, do I need to add

1.2.3.4    example.com
1.2.3.4    www.example.com
1.2.3.4    smtp.example.com
1.2.3.4    pop.example.com
...

Or will just adding

1.2.3.4    example.com

suffice?

4

You will need to specify each and every subdomain. If that is not what you want, you should look into installing a real DNS server (e.g. bind9).

This is rather easy to check by first adding just example.com to /etc/hosts and then do

ping -c 2 example.com
ping -c 2 www.example.com

The first will succeed with the provided IP address. The second will go to 93.184.216.119 (the IP address in the internet for www.example.com)

3

/etc/hosts is/was the precursor to the DNS system from when the Internet was in it's infancy. It's still used today for situation such as when you want to resolve a small number of local systems or in a development setup where you haven't set up DNS.

You place all hostnames that you want to resolve to an IP address in it. You can allocate multiple names to one IP address as the localhost line in most distros have:

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4

If you want to add 1.2.3.4 to be your webserver, which is called www.example.com and also access it via a shorter www then add:

1.2.3.4   www www.example.com

In your instance, you can place all the names on one line:

1.2.3.4 www.example.com smtp.example.com pop.example.com

The order in which your system resolves these names (/etc/hosts or DNS first) can be configured in the hosts: line of /etc/nsswitch.conf)

But remember, /etc/hosts only works from your machine. If you have a few systems, editing /etc/hosts on each can become unwieldly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.