- Файл hosts на Linux
- Как отредактировать файл hosts в Linux
- Hosts files on linux
- NAME
- SYNOPSIS
- DESCRIPTION
- FILES
- NOTES
- EXAMPLE
- SEE ALSO
- How to Edit Hosts File on Linux Mint 21
- What Is the Purpose of Hosts File in Linux Mint 21
- How to Edit the Hosts File in Linux Mint 21
- How to Block a Website through Hosts File
- Conclusion
- About the author
- Aaliyan Javaid
- 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.
Hosts files on linux
NAME
hosts - static table lookup for hostnames
SYNOPSIS
DESCRIPTION
This manual page describes the format of the /etc/hosts file. This file is a simple text file that associates IP addresses with hostnames, one line per IP address. For each host a single line should be present with the following information: IP_address canonical_hostname [aliases. ] Fields of the entry are separated by any number of blanks and/or tab characters. Text from a "#" character until the end of the line is a comment, and is ignored. Host names may contain only alphanumeric characters, minus signs ("-"), and periods ("."). They must begin with an alphabetic character and end with an alphanumeric character. Optional aliases provide for name changes, alternate spellings, shorter hostnames, or generic hostnames (for example, localhost). The Berkeley Internet Name Domain (BIND) Server implements the Internet name server for UNIX systems. It augments or replaces the /etc/hosts file or hostname lookup, and frees a host from relying on /etc/hosts being up to date and complete. In modern systems, even though the host table has been superseded by DNS, it is still widely used for: bootstrapping Most systems have a small host table containing the name and address information for important hosts on the local network. This is useful when DNS is not running, for example during system bootup. NIS Sites that use NIS use the host table as input to the NIS host database. Even though NIS can be used with DNS, most NIS sites still use the host table with an entry for all local hosts as a backup. isolated nodes Very small sites that are isolated from the network use the host table instead of DNS. If the local information rarely changes, and the network is not connected to the Internet, DNS offers little advantage.
FILES
NOTES
Modifications to this file normally take effect immediately, except in cases where the file is cached by applications. Historical notes RFC 952 gave the original format for the host table, though it has since changed. Before the advent of DNS, the host table was the only way of resolving hostnames on the fledgling Internet. Indeed, this file could be created from the official host data base maintained at the Network Information Control Center (NIC), though local changes were often required to bring it up to date regarding unofficial aliases and/or unknown hosts. The NIC no longer maintains the hosts.txt files, though looking around at the time of writing (circa 2000), there are historical hosts.txt files on the WWW. I just found three, from 92, 94, and 95.
EXAMPLE
127.0.0.1 localhost 192.168.1.10 foo.mydomain.org foo 192.168.1.13 bar.mydomain.org bar 146.82.138.7 master.debian.org master 209.237.226.90 www.opensource.org
SEE ALSO
hostname(1), resolver(3), resolver(5), hostname(7), named(8) Internet RFC 952
How to Edit Hosts File on Linux Mint 21
Host file of Linux mint primarily maps the IP address with the domain names of the system thus making it useful for various purposes which include blocking a website and accessing any computer remotely. If you are unaware of how to edit a host file in your Linux Mint 21 and want to use it for multiple purposes, then read this guide.
What Is the Purpose of Hosts File in Linux Mint 21
Host file as mentioned above contains the IP addresses and hostname of the Linux system, but there are multiple uses of host file and those are:
- Blocking any websites
- Remotely accessing any Alias
- Blocking advertisers and trackers
- Testing an application
- Adding or blocking specific networks
How to Edit the Hosts File in Linux Mint 21
The process of editing the host file of Linux Mint 21 is quite easy; open the host file on your Linux Mint 21 by using any terminal-based text editor, for example, nano:
Now edit the host file by entering the data like IP addresses and host names for the connections you either want to block or access.
How to Block a Website through Hosts File
When it comes to security or parental control hosts file plays a crucial role as it can be used to block unwanted websites. The process of blocking a website is mentioned below:
For instance, if you want to block YouTube then use:
Next save the file and open the website on the browser of Linux Mint to see if the site is blocked or not:
Conclusion
Host files in an operating system generally contain the IP address and the domain name of that system, there are multiple uses of a host file which can be achieved by editing it and it can be done by stating its path with nano command.
About the author
Aaliyan Javaid
I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.
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.