- Файл hosts на Linux
- Как отредактировать файл hosts в Linux
- The /etc/hosts File Complete Guide for Linux
- What Is the /etc/hosts File and What is its Purpose?
- What will we Cover?
- Use Cases of the Hosts File
- Format of the /etc/hosts File
- Application of the Hosts File
- Access Control Files
- Security Issues of the Hosts File
- Conclusion
- About the author
- Ali Imran Nagori
- The Hosts File on Linux
- Why Edit /etc/hosts file?
- How to Edit /etc/hosts file?
- Block a Website
- Access Remote Computer through an Alias
Файл hosts на Linux
В этой статье мы расскажем, что такое файл hosts Linux, как его использовать и как изменить файл hosts в Linux.
Данные любого сайта находятся на физическом сервере. Чтобы браузер нашёл нужный сервер, он должен знать его IP-адрес. Узнать, какому IP соответствует домен, можно с помощью DNS-системы. DNS ― это своеобразная телефонная книга, где записаны абсолютно все домены и соответствующие им IP-адреса. До появления DNS использовался hosts. Hosts ― это текстовый файл, в котором находятся данные домена и его IP.
С появлением DNS hosts поменял сферу применения. Настройки в файле для браузера более приоритетны. Поэтому, перед тем как обратиться к DNS, браузер проверяет настройки hosts. Если в файле нет никаких данных по нужному хосту (домену), браузер обращается к DNS-системе. Эту особенность можно использовать. С помощью файла hosts можно:
- Указать псевдоним для локальной сети.
- Запретить посещение какого-либо сайта. Такой метод часто применяется на рабочих компьютерах, чтобы сотрудники не отвлекались на развлекательные сайты. Также ограничения можно установить для детских устройств. Например, вы не хотите, чтобы ребёнок посещал сайт youtube.com, впишите в hosts 127.0.0.1 youtube.com. 127.0.0.1 ― эта запись заставляет систему обращаться к собственному компьютеру.
- Просмотреть сайт до внесения его в DNS-систему. Если вы прописали DNS-серверы для домена, изменения вступят в силу в течение 24 часов. В некоторых случаях увидеть свой сайт нужно быстрее. Для этого вручную впишите свой домен и соответствующий ему IP. Тогда браузеру будет неважно, есть ли данные о этом сайте в единой системе.
Как добавить нужные данные, мы расскажем в инструкции ниже.
Как отредактировать файл hosts в Linux
В Linux файл hosts находится в папке /etc/hosts. Обратите внимание! Обычно для редактирования hosts нужен доступ суперпользователя.
Чтобы отредактировать его:
Hosts Linux настройка
123.123.123.123 faq-reg.ru www.faq-reg.ru
- 123.123.123.123 — IP-адрес сервера или хостинга,
- faq-reg.ru — имя домена.
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.
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:
- 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.
- 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.
- 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.
- When edited in a proper manner, the Hosts file can operate as a security firewall for a system.
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:
- Refer to the hosts.allow file: it sequentially reads this file and executes the first rule stated for that service.
- 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.
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
.
The Hosts File on Linux
All operating systems with network support have a hosts file to translate hostnames to IP addresses. Whenever you open a website by typing its hostname, your system will read through the hosts file to check for the corresponding IP and then open it. The hosts file is a simple text file located in the /etc folder on Linux and Mac OS (/etc/hosts). Windows has a hosts file as well, on Windows you can find it in Windows\System32\drivers\etc\
Here is how it looks like:
From what we mentioned, you might expect this file to have a very long list of IPs and corresponding hostnames; but that is not true. The hosts file only contains several lines;
- The first part, by default, contains the hostnames and IP addresses of your localhost and machine. This is the part you will usually modify to make the desired changes.
- The second part has information about IPv6 capable hosts and you will hardly be editing these lines.
Whenever you type an address, your system will check the hosts file for its presence; if it is present, you will be directed to the corresponding IP. If the hostname is not defined in the hosts file, your system will check the DNS server of your internet to look up for the corresponding IP and redirect you accordingly.
Why Edit /etc/hosts file?
By editing the hosts files, you can achieve the following things:
- Block a website
- Handle an attack or resolve a prank
- Create an alias for locations on your local server
- Override addresses that your DNS server provides
- Control access to network traffic
How to Edit /etc/hosts file?
You can edit the hosts text file located at /etc/hosts only as a superuser. You will first have to open it in text editors such as VI editor, Nano editor or gedit, etc. in the Linux terminal. You will then make the required changes and save the file for these changes to take effect.
In this article, we will use the Nano editor to edit the file. Please type the following command:
As mentioned before, we will edit the first part of the hosts file where IP addresses and hostnames are defined. We will explain the following two ways in which you can make use of the hosts file:
Block a Website
You can block a website by redirecting it to the IP of your localhost or the default route.
For example, if we want to block google.com, we can add the following text to our file:
Now when we open the google website, our system will take the IP of our localhost (127.0.0.1) from the hosts file and redirect us to that instead of the google IP from our DNS server.
Now when we open the google website, our system will take the IP of the default route (0.0.0.0) from the hosts file and redirect us to that instead of the google IP from our DNS server.
This is how the edited file will look like. Please save the changes by hitting ctrl+X.
Now when you try to open www.google.com from your browser, you will see an error message as follows:
Please note that we have defined the complete address www.google.com instead of just the hostname google.com in the hosts file because modern browsers sometimes circumvent the block if we only define the latter.
There are also some predefined blocklists available that you may use in your hosts file: https://github.com/StevenBlack/hosts
Access Remote Computer through an Alias
Suppose we have a server located on a local network that we want to access. We usually have to type the server’s IP to access it unless it has been defined on our local DNS. One way to avoid typing the IP, again and again is to assign an alias to the server in the hosts file as follows:
The IP corresponds to the location of the server we want to access, and myserver is the new alias we want to use.
When we save the file and type myserver in the address bar, we will be redirected to our remote server.
We have learned that by making very simple changes to the hosts file, we can customize and thus redirect the network traffic according to our needs. We can also eliminate a network attack or prank by restoring the hosts file to its default.