Hosts file in linux server

What is the Purpose of /etc/hosts File in Linux

The /etc/hosts file is an integral part of the Linux system. But what is it used for?

The /etc/hosts file in Linux or any other operating system is used to map connections between IP addresses and domain names.

Quite a generic answer right? Well, this guide is going to get some feet deeper so everyone can benefit from its offering.

What is the /etc/hosts file in Linux?

In the earlier days of networking, the /etc/hosts file was used to translate the IP addressed (8.8.8.8) to human-readable form (www.google.com) and over time it lost its relevance. In modern systems, the whole process of resolving domain names is done through DNS (Domain Name System).

Then why do we still get the hosts file in every operating system?

Rarely but still being used in given cases:

  • When you want to block certain websites.
  • It can be used as a backup in the case when DNS is broken.
  • You can also use it as a local DNS server.

You can think of many other tasks such as blocking ads, enhancing local firewalls, and many other tasks that involve the usage of IPs and DNS!

So now it’s time for some practical examples of how you can utilize the /etc/hosts file.

Use the /etc/hosts file to redirect URLs

The hosts file needs two components to work: domain name and IP.

So what I’m going to do is use the DNS of itsfoss and will redirect it to the IP of LHB.

For that, I’ll be using the ping command to find the IP of LHB:

use ping command in linux

Now, let’s open the hosts file (I’m using the nano text editor here):

how to redirect url in linux

It is considered good practice to have both!

Now, when I pinged itsfoss, it is being redirected to the IP of Linuxhandbook:

traffic has been redirected to different IP in linux

You can use this method for migrating your website from one server to another. Before you actually change the DNS of the website to the new server, you make all the changes on the new server which is accessible through the domain name on your system.

Gridpane uses this trick for migrating WordPress websites.

Block unwanted websites using the /etc/hosts file

So what I’m going to do here is assign my local domain to the sites that I no longer want to use!

For example, I’ll be blocking Facebook! So let’s get the IP address of Facebook:

check ip using ping command in linux

Now, let’s open the hosts file:

block specific website in linux using the hosts file

And when I used the browser to access Facebook, it showed me this:

Читайте также:  Timeshift linux из консоли

Create Website shortcuts using the /etc/hosts file

In this example, I’ll be creating a shortcut for Linuxhandbook named lhb.com .

The first step will be similar to what I explained earlier (getting the IP of a domain):

use ping command to check connectivity of domain

Now, let’s modify the hosts file by the given command:

And make changes as given:

create website shortcuts using hosts file in linux

Once you’re done, you put it to the test. I’m using the ping command with a recently made shortcut.

how to create url shortcuts using the hosts file in linux

As you can clearly see, there’s no difference between the IP of the original domain and the shortcut.

Wrapping Up

In this tutorial, I explained the purpose behind having a hosts file and some examples of how you can tweak DNS settings to suit yourself using the hosts file.

And if you still have any queries, the comments section is open for discussion.

Источник

The /etc/hosts File Complete Guide for Linux

What Is the /etc/hosts File and What is its Purpose?

The /etc/hosts or simply the Hosts file is a plain text file that maps IP addresses with their corresponding hostnames. Primarily, the Hosts file is useful when you are working on a local network of computers. It provides some simple sort of hostname resolution.

The /etc/hosts file is usually useful when we are not using DNS or NIS service for resolving IP addresses. In fact, when DNS did not exist, there were no centralized systems for resolving hostnames. Local networks and computers relied on their Hosts file. This file holds the entries for all the known hostnames and their corresponding IP addresses.

After DNS appeared on the scene, computers did not need this file and started using the DNS service for fetching hostnames. Despite these advances, the Hosts file is still relevant on modern operating systems.

What will we Cover?

In this guide, we will see what a Hosts file in Linux is, some use cases of this file, and an application of this file based on the use cases.

Use Cases of the Hosts File

We can assign a domain name to an IP address using the Hosts file. However, these changes are local and will work on the local computer.

The Hosts file is still relevant today, there are some specific use cases for the Hosts file as mentioned below:

  1. We have built a website, but it is not live on the web since we have not registered the domain name for it. However, if we have a registered IP address from our hosting, we can map this IP to a dummy or non-existing domain name and continue building our website. Similarly, in a software testing environment, many web applications run on the local hosts address i.e. addresses of the type 127.0.0.1. Again, we can manage this using the Hosts file.
  2. In case we have migrated our website from one hosting to another one and we want to check the new hosting performance, we can connect our domain to the new hosting without closing our old hosting account. In this way, we can see how our website is loading from the new hosting.
  3. Suppose you want to block a website, like blocking Facebook on an educational system. We can easily do this by mapping the target domain name to an invalid address IP like 0.0.0.0. This will create a loopback. This is usually helpful for blocking non-educational websites in universities or blocking mature content for kids.
  4. When edited in a proper manner, the Hosts file can operate as a security firewall for a system.
Читайте также:  Температура процессора команда linux

Format of the /etc/hosts File

The Hosts file is located inside the /etc folder. The entries of the file are per line basis. For instance, every single line consists of a hostname followed by its IP address:

The IP addresses used here are either IPv4 or IPv6. These addresses and hostnames maintain a distance of any number white space or a distance of a tab character.

On all operating systems, the Hosts file has the same format. Let us see the contents of the file on a Linux system:

# The following lines are desirable for IPv6 capable hosts
:: 1 ip6-localhost ip6-loopback
fe00:: 0 ip6-localnet
ff00:: 0 ip6-mcastprefix
ff02:: 1 ip6-allnodes
ff02:: 2 ip6-allrouters

The Hosts file contains the entries for both the IPv4 and IPv6 addresses.

Application of the Hosts File

As mentioned earlier, we can use the Hosts file for blocking a domain. Let us take the case of blocking Youtube. Open the file:

Use the tab character to insert space between the IP address and its corresponding domain name.

Now, save and close the file. Open any web browser and try to navigate to youtube and see what happens:

We can see youtube.com is blocked and we are getting an ‘Unable to connect’ message. To unblock the site, we have to simply remove the above entry from the /etc/hosts file.

Access Control Files

Besides the plain Hosts file, we also have a /etc/hosts.allow file and a /etc/hosts.deny file.

These files, referred to as hostess access files, are used by TCP wrappers. These files decide whether a client machine can connect to a host.

When a TCP wrapped service gets a client request, it performs the actions below:

  1. Refer to the hosts.allow file: it sequentially reads this file and executes the first rule stated for that service.
  2. Refer to the hosts.deny file: it sequentially reads this file and if a matching rule is found, it does not accept the connection request. Otherwise access is granted to the requesting service.

The hosts.allow file decides which IP addresses can connect to a host. The /etc/hosts.deny file is used in conjunction with it.

Security Issues of the Hosts File

Although the Hosts file looks like a simple file, in some cases, for example, on Windows systems, malware like adware or spyware modifies the Hosts file to take the users to malicious websites.

If you are unsure about the health of your Hosts file, you can use Lynis system auditor for Linux. Lynis has its built-in test build for checking the security strength of your Linux system.

Also, try to keep the Hosts file at a minimum length. If you have too many systems declared inside the Hosts file, you should consider placing them in a different DNS zone.

Conclusion

The Hosts file is an old file on Linux, but still, it is a powerful utility. Right from local name resolving, it is an important part of many software and their development process. In this article, we have seen a basic introduction to the Hosts file in Linux. We have also shown how to block a website using the Hosts file. Also, we can use it to block banners, adware, and other third party page counters.

Читайте также:  Аналог a под linux

After reading this article, you should now know how to use the Hosts file for managing DNS queries as per our requirements.

About the author

Ali Imran Nagori

Ali imran is a technical writer and Linux enthusiast who loves to write about Linux system administration and related technologies. You can connect with him on LinkedIn
.

Источник

Файл hosts на Linux

В этой статье мы расскажем, что такое файл hosts Linux, как его использовать и как изменить файл hosts в Linux.

Данные любого сайта находятся на физическом сервере. Чтобы браузер нашёл нужный сервер, он должен знать его IP-адрес. Узнать, какому IP соответствует домен, можно с помощью DNS-системы. DNS ― это своеобразная телефонная книга, где записаны абсолютно все домены и соответствующие им IP-адреса. До появления DNS использовался hosts. Hosts ― это текстовый файл, в котором находятся данные домена и его IP.

С появлением DNS hosts поменял сферу применения. Настройки в файле для браузера более приоритетны. Поэтому, перед тем как обратиться к DNS, браузер проверяет настройки hosts. Если в файле нет никаких данных по нужному хосту (домену), браузер обращается к DNS-системе. Эту особенность можно использовать. С помощью файла hosts можно:

  1. Указать псевдоним для локальной сети.
  2. Запретить посещение какого-либо сайта. Такой метод часто применяется на рабочих компьютерах, чтобы сотрудники не отвлекались на развлекательные сайты. Также ограничения можно установить для детских устройств. Например, вы не хотите, чтобы ребёнок посещал сайт youtube.com, впишите в hosts 127.0.0.1 youtube.com. 127.0.0.1 ― эта запись заставляет систему обращаться к собственному компьютеру.
  3. Просмотреть сайт до внесения его в DNS-систему. Если вы прописали DNS-серверы для домена, изменения вступят в силу в течение 24 часов. В некоторых случаях увидеть свой сайт нужно быстрее. Для этого вручную впишите свой домен и соответствующий ему IP. Тогда браузеру будет неважно, есть ли данные о этом сайте в единой системе.

Как добавить нужные данные, мы расскажем в инструкции ниже.

Как отредактировать файл hosts в Linux

В Linux файл hosts находится в папке /etc/hosts. Обратите внимание! Обычно для редактирования hosts нужен доступ суперпользователя.

Чтобы отредактировать его:

Как отредактировать файл hosts в Linux 1

Hosts Linux настройка

123.123.123.123 faq-reg.ru www.faq-reg.ru
  • 123.123.123.123 — IP-адрес сервера или хостинга,
  • faq-reg.ru — имя домена.

Как отредактировать файл hosts в Linux 2

Ubuntu файл hosts

Файл hosts редактируется одинаково во всех Unix-системах.

Google Chrome может игнорировать файл hosts. Если вы хотите заблокировать какой-либо сайт в этом браузере, вводите http:// в начале каждого адреса. Например, вводите не youtube.com, а http:/youtube.com. При таких настройках Google Chrome не будет игнорировать hosts.

Если вы не хотите разбираться, как работать с файлом hosts, но заблокировать нежелательные сайты нужно, воспользуйтесь приложением Linux Mint Domain Blocker. Оно самостоятельно добавит домены, которые нужно заблокировать, в файл hosts. Эта программа пользуется тем же способом, что и пользователь при ручной блокировке. Linux Mint Domain Blocker вместо правильного IP добавляет 127.0.0.1.

Источник

Оцените статью
Adblock
detector