- Как отредактировать файл Hosts в Linux, Windows и macOS
- How to Edit Your Hosts File on Linux, Windows, and macOS
- В этом руководстве мы расскажем, как изменить файл hosts в Linux, macOS и Windows.
- Формат файла хостов
- Изменить файл хостов в Linux
- Изменить файл хостов в Windows
- Изменить файл хостов в macOS
- Вывод
- How to Setup Local DNS Using /etc/hosts File in Linux
- Understanding Name Service Switch in Linux
- Configure DNS Locally Using /etc/hosts File in Linux
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Файл hosts в Linux
- Разрешение доменных имён в Linux
- Настройка файла hosts в Linux
- Выводы
- How to Edit Hosts File on Linux?
- Why Edit Hosts File?
- How to Edit Hosts File on Linux?
- Block a Website
- Name Service Switch
- Conclusion
- About the author
- Simran Kaur
Как отредактировать файл Hosts в Linux, Windows и macOS
How to Edit Your Hosts File on Linux, Windows, and macOS
В этом руководстве мы расскажем, как изменить файл hosts в Linux, macOS и Windows.
Файл hosts используется для сопоставления доменных имен (имен хостов) с IP-адресами. Это простой текстовый файл, используемый всеми операционными системами, включая Linux, Windows и macOS.
Файл hosts имеет приоритет над DNS. Когда вы вводите доменное имя веб-сайта, который вы хотите посетить, доменное имя должно быть преобразовано в соответствующий IP-адрес. Операционная система сначала проверяет свой файл hosts на наличие соответствующего домена, и, если запись для домена отсутствует, она запрашивает у настроенных DNS-серверов разрешение указанного имени домена. Это влияет только на компьютер, на котором вносятся изменения, а не на то, как домен разрешается во всем мире.
Использование файла hosts для сопоставления домена с IP-адресом особенно полезно, когда вы хотите протестировать свой веб-сайт без изменения настроек DNS домена. Например, вы переносите свой веб-сайт на новый сервер и хотите проверить его работоспособность, прежде чем указывать домен на новый сервер. Файл hosts также можно использовать для блокировки веб-сайтов на вашем компьютере.
Формат файла хостов
Записи в файле hosts имеют следующий формат:
Чтобы добавить запись в файл hosts, просто откройте файл в текстовом редакторе. Ниже приведен пример файла hosts:
Чтобы отменить изменения, просто откройте файл и удалите добавленные вами строки.
Изменить файл хостов в Linux
В Linux полный путь к файлу /etc/hosts .
Приведенные ниже инструкции действительны для всех дистрибутивов Linux, включая Ubuntu, CentOS, RHEL, Debian и Linux Mint:
В окне терминала откройте файл hosts с помощью вашего любимого текстового редактора :
При появлении запроса введите свой пароль sudo.
Прокрутите вниз до конца файла и добавьте новые записи:
Изменить файл хостов в Windows
В Windows полный путь к файлу c:\Windows\System32\Drivers\etc\hosts . Приведенные ниже инструкции действительны для Windows 10 и Windows 8.
Нажмите клавишу Windows и введите Блокнот в поле поиска.
Щелкните правой кнопкой мыши значок «Блокнот» и выберите «Запуск от имени администратора».
В Блокноте нажмите Файл, затем Открыть. В поле Имя файла вставьте c:\Windows\System32\drivers\etc\hosts .
Прокрутите вниз до конца файла и добавьте новые записи:
Сохраните изменения, нажав File > Save .
Изменить файл хостов в macOS
В macOS полный путь к файлу /etc/hosts . Приведенные ниже инструкции действительны для всех версий MacOS.
В окне терминала откройте файл hosts с помощью вашего любимого текстового редактора:
При появлении запроса введите свой административный пароль.
Прокрутите вниз до конца файла и добавьте новые записи:
Сохраните изменения и очистите кэш DNS:
Вывод
Файл hosts позволяет вам установить IP-адрес данного доменного имени.
How to Setup Local DNS Using /etc/hosts File in Linux
DNS (Domain Name System or Service) is a hierarchical decentralized naming system/service that translates domain names into IP addresses on the Internet or a private network and a server that provides such a service is called a DNS server.
This article explains, how to setup a local DNS using the hosts file (/etc/hosts) in Linux systems for local domain resolution or testing the website before taking live.
For example, you may want to test a website locally with a custom domain name before going live publicly by modifying the /etc/hosts file on your local system to point the domain name to the IP address of the local DNS server you configured.
The /etc/hosts is an operating system file that translate hostnames or domain names to IP addresses. This is useful for testing websites changes or the SSL setup before taking a website publicly live.
Attention: This method will only work if the hosts have a static IP address. Therefore ensure that you have set static IP addresses for your Linux hosts or nodes running other operating systems.
For the purpose of this article, we will be using the following domain, hostnames and IP addresses (use values that apply to your local setting).
Understanding Name Service Switch in Linux
Before moving any further, you should understand a few things about another important file that is /etc/nsswitch.conf. It provides Name Service Switch functionality which controls the order in which services are queried for name service lookups.
The configuration is based on order; if files is before dns it means the system will query the /etc/hosts file before checking DNS for name service requests. But if DNS is before files then the domain lookup process will consult DNS first before any other appropriate services or files.
In this scenario, we want to query the “files” service. To check the order, type.
Check Name Service Switch
Configure DNS Locally Using /etc/hosts File in Linux
Now open the /etc/hosts file using your editor of choice as follows
Then add the lines below to the end of the file as shown in the screen shot below.
Next, test if everything is working well as expected, using the ping command from Host 1, you can ping Host 2 using it domain name like so.
Ping Domain Locally
On the Host 2, we have setup Apache HTTP server. So we can also test if the name translation service is working as follows by going to URL http://centos.tecmint.lan.
Check Domain Locally
Important: To use the domain names on any host on the network, you must configure the above settings in its /etc/hosts file.
What does this mean, in the above example, we only configured the hosts file of Host 1 and we can only use the domain names on it. To use the same names on Host 2, we have to add the addresses and names to its hosts file as well.
Lastly, you should use host command or nslookup command to test if the name translation service is actually working, these commands only query DNS and overlook any configurations in /etc/hosts and /etc/nsswitch.conf files.
You may also like to read these following related articles.
That’s it! Do share any additional thoughts or questions about this topic with us, via the comment section below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Файл hosts в Linux
Система доменных имен DNS используется для определения, какой IP принадлежит к нужному домену в сети интернет. Когда какой-либо программе понадобится обратиться к сайту по его доменному имени, операционная система отправляет к DNS-серверу запрос, чтобы узнать, по какому IP ей дальше передавать пакеты. Но так происходит не всегда. Например, когда мы обращаемся к домену localhost, то всегда запрос отправляется нашему локальному компьютеру.
Всему причиной файл hosts. Если вы раньше пользовались Windows, то, наверное, уже слышали о таком файле. Там чаще всего он использовался для того, чтобы быстро заблокировать доступ к какому-либо ресурсу. Но применение его гораздо шире. В этой статье мы рассмотрим, как настроить файл hosts в Linux, а также какие возможности он нам предоставляет.
Разрешение доменных имён в Linux
Прежде чем мы перейдём к самому файлу hosts, нужно разобраться, как происходит поиск IP-адреса для доменного имени в Linux. Я говорил, что операционная система сразу же отправляет запрос DNS-серверу, но это не совсем так. Существует определённый порядок поиска, согласно которому он выполняется. Этот порядок установлен в конфигурационном файле /etc/nsswitch.conf
Здесь нас интересует строчка hosts. В ней в порядке очередности записаны службы, которые используются для поиска IP-адреса для доменного имени. Пункт files означает использование файла /etc/hosts, а dns — сервиса доменных имён интернета. Если files расположена перед hosts, это означает, что сначала система попытается найти домен в /etc/hosts, а уже потом по DNS. По умолчанию дело обстоит именно так.
Настройка файла hosts в Linux
Нужный нам файл находится в директории /etc/. Для его открытия можно использовать любой текстовый редактор как в командной строке, так и в графическом интерфейсе, только открывать его нужно с правами суперпользователя. Например, с помощью vim:
sudo vi /etc/hosts
sudo gedit /etc/hosts
Синтаксис файла довольно простой. В нём находится несколько строчек с доменными именами и IP-адресами, которые нужно для них использовать. Каждая из них выглядит вот так:
ip_адрес домен алиас
Обычно первая же строчка создаёт правило для перенаправления всех запросов к домену localhost на локальный IP-адрес — 127.0.0.1:
Также в этом файле по умолчанию размещаются перенаправления для имени вашего компьютера и для IPv6-адресов. Вы можете создать свои настройки для любого нужного домена. Для этого нужно добавить строчку в конец файла. Например, направим все запросы к домену losst.pro на ip 127.0.0.1:
Обратите внимание, что здесь указывается только домен, без протокола. Префикс http или https указывать не нужно, иначе ничего работать не будет. А вот для поддомена www нужно создавать отдельную запись или записывать его в виде алиаса. Например:
127.0.0.1 losst.pro www.losst.pro
Теперь при запросе домена losst.pro будет открываться наш локальный IP. Чтобы вернуть доступ к оригинальному ресурсу, достаточно убрать добавленную строчку. Но вы можете использовать не только локальный адрес, но и любой другой. Это очень удобно, если вы только зарегистрировали домен и доменная зона ещё не успела обновиться, а вы уже хотите работать с новым сайтом. Просто добавьте данные в /etc/hosts и работайте как обычно.
Выводы
В этой небольшой статье мы разобрали, как выполняется настройка DNS через файл hosts Linux. Как видите, с его помощью вы можете блокировать доступ к нежелательным ресурсам, например, к которым программы не должны получить доступ, а также использовать его в работе веб-мастера.
How to Edit Hosts File on Linux?
A Hosts file is supported in Linux, Windows, and Mac; they are plain-text files that work to map hostnames to various IP addresses. It is great to edit the Hosts file when you run the test on the specific network. You can also use the mapping of an IP address to skip the process in which the web browser uses the DNS (Domain Name Server) lookup for translating a domain name to a particular IP address.
When a user types a website’s domain name, the domain name needs to translate into a specific IP address. A Hosts file has a top priority over DNS since an operating system checks its Hosts file for a domain and in case there is no entry for that domain. It starts to query the configured DNS servers for resolving the particular domain name. It was the little information about the Hosts file, and we will consider every single aspect on how to edit Hosts files on Linux easily.
Why Edit Hosts File?
There are various reasons for editing hosts file in the Linux machine:
- You can easily block a website.
- You can handle an attack.
- You can create an alias for different locations on a local server.
- You can override addresses that a DNS server delivers.
- You can easily control access to network traffic.
How to Edit Hosts File on Linux?
Open the terminal from applications > utilities > terminal feature, or you can use CTRL, ALT, and T as shortcut keys.
After opening the terminal, open the Linux Hosts file in the system using the following command:
We have used Vim, but you can use different text editors like nano.
Once you execute the command, the system will prompt you to enter the password to open the Hosts file.
You can easily modify the Hosts file, so the file is formatted like the IP address is written first, and the server’s name is on second.
You can add entries at the end of the Hosts file as per your requirements. In case you want to ignore any line or specify the system to not read the line, then you can put the “#” sign at the starting of that particular line. Finally, you can save the file before and make sure you save it before exiting.
Block a Website
If you want to block a particular website from redirecting it to the localhost’s IP address, change the Hosts file’s domain name. For example, we want to block xxyyzz.com, then we can write:
In the above text, 134.1.0.1 is the IP of the localhost, but if you want to make changes in the default route, then you can write:
In the above text, 0.0.0.0 IP is a default route from this particular Hosts file.
At last, you can press CTRL and X keys simultaneously to save the file.
Name Service Switch
As mentioned, a Hosts file works to bypass a Domain Namer server lookup. Still, it has another file that has the information of the operating system about the order for finding the IP address translation.
The nsswitch.conf is a file completely configured for finding the DNS, then skips the Hosts file and goes in the DNS lookup. You can use the below command line for configuration checking easily:
$ cat etc nsswttch.conf
# /etc/nsswitch.conf
#
# Example configuration of GNU Name Service Switch functionality.
# If you have the ‘glibc-doc-reference’ and ‘info’ packages installed, try:
# ‘info libc «Name Service Switch»‘ for information about this file.
passwd: compat systemd
group: compat systemd
shadow: compat
gshadow: files
hosts: files mdns4_minimal [ NOTFOUND = return ] dns myhostname files
networks: db files
protocols: db files
services: db files
ethers: db files
rpc: db files
netgroup: nis
xyz @ xyz-VirtualBox:
There is an entry called “Hosts,” ensuring that the files should be listed in the right-hand column in the above results. In case it is not listed like this, then open your file editor using the below command:
This command will open the Vim text editor to make changes and set the files at the beginning for appropriate use.
Conclusion
The Hosts files are beneficial to perform multiple tasks for domain names and IP addresses. It was the complete information on the Hosts file and how you can easily edit the Hosts file on Linux. This procedure is tried and tested on multiple Linux machines, but you have to carefully follow every step.
About the author
Simran Kaur
Simran works as a technical writer. The graduate in MS Computer Science from the well known CS hub, aka Silicon Valley, is also an editor of the website. She enjoys writing about any tech topic, including programming, algorithms, cloud, data science, and AI. Travelling, sketching, and gardening are the hobbies that interest her.