- Как найти и отредактировать файл Hosts
- Редактирование:
- Бесплатный DNS-хостинг
- Расположение hosts-файла в различных ОС:
- Windows
- How to Lock, Manage, Edit Hosts File in Windows 10
- Hosts File in Windows 10
- Host file location
- Lock Hosts file to prevent hijacking
- Block website using the Hosts file
- Edit Hosts file
- HostsMan
- Где находится файл hosts и как его изменить
- Зачем нужен файл hosts
- Где находится файл hosts
- Как внести изменения в файл hosts
- Блокировка доступа к сайту через файл hosts
- Оригинальный файл hosts и как его восстановить
- How to Edit the Hosts File in Windows
- What Does The Hosts File Do?
- Why Edit The Hosts File?
- Windows Hosts File Location
- How To Edit The Hosts File
- Opening The Hosts File
- Editing The Hosts File
- Saving The Hosts File
Как найти и отредактировать файл Hosts
В некоторых случаях бывает необходимо отредактировать файл hosts на локальном ПК или удаленном сервере. С помощью этого файла вы можете управлять маршрутизацией трафика и разрешением IP-адресов в имена DNS. Приоритет данного файла позволяет обрабатывать сетевые запросы до их передачи публичным или частным DNS-серверам. Таким образом, реализуется возможность создания своеобразной локальной системы DNS на самой машине.
Сегодня данный файл практически не используется, его функции выполняет служба DNS, преобразующая «имя в адрес» и «адрес в имя». Тем не менее, его использование возможно и сегодня.
Редактирование:
Синтаксис остается одинаковым для всех операционных систем. У большинства файлов hosts несколько записей для loopback (обратной петли). Мы используем это для примера.
Бесплатный DNS-хостинг
- Надёжные DNS-сервера
- Автоматическая миграция
- API
Часть 1: адрес, куда перенаправить;
Часть 2: адрес, который вы хотите перенаправить;
Часть 3: комментарий.
Они могут быть разделены пробелом, но для удобства чтения, как правило, разделены одним или двумя горизонтальными табуляциями.
127.0.0.1 localhosts #loopback
Используйте любой текстовый редактор в привилегированном режиме для внесения изменений.
Расположение hosts-файла в различных ОС:
Windows
В данном примере будет запрещен доступ машины к сайту Facebook и его поддоменам. Это реализуется за счет разрешения запросов DNS на имя facebook.com в несуществующий IP-адрес 0.0.0.0:
При попытке перейти по заблокированному адресу после добавления строки выше в файл hosts вы увидите ошибку, подтверждающую корректность конфигурации:
How to Lock, Manage, Edit Hosts File in Windows 10
The Hosts file in Windows 10/8/7, is used to map hostnames to IP addresses. This Hosts file is located deep down in the Windows folder. It is a plain text file, and the size of the original default Hosts file is around 824 bytes.
Hosts File in Windows 10
In this post, we will see its location and also how to manage, lock, or edit the Hosts file.
Host file location
The Hosts file in Windows is located at the following location:
Lock Hosts file to prevent hijacking
Imagine clicking on www.thewindowsclub.com and seeing a completely different website load in your browser. Malware can redirect Web addresses on your computer by altering your Hosts file. This is referred to as the Host File Hijack.
To prevent Host file hijacks, you may navigate to it, right-click on it, select Properties and make it a Read-only file. This will lock down your Hosts file and prevent anyone or any malware from writing to it.
Block website using the Hosts file
To block a website using the Hosts File, simply add the following entry:
Although I do not do it, many users like to manually add entries to it in order to block the opening of one or more particular websites. Others, like to download and use List from well-known sources like mvps.org, to add entries which block malware sites from opening.
Edit Hosts file
If you need to edit the Hosts file, navigate to the following folder location:
Here you will see the Hosts file. Right-click on it and select Notepad. Make the changes and Save.
But sometimes, even when you are logged on with administrative credentials, you may receive the following error message:
Access to C:\Windows\System32\drivers\etc\ hosts was denied
Cannot create the C:\Windows\System32\drivers\etc\hosts file. Make sure that the path and file name are correct.
In this case, type Notepad in Start search and right-click on the Notepad result. Select Run as administrator. Open the Hosts file, make the necessary changes, and then click Save.
HostsMan
While you can always manually manage or edit Hosts file manually, I would like to suggest that you use a third-party freeware tool like HostsMan to do it.
HostsMan is a feature-rich tool that lets you add, remove, edit entries in the Hosts file. It also lets you easily add third-party Hosts lists that help in blocking malware sites and lets you easily enable or disable the hosts file. It includes a built-in hosts file updater & a hosts editor. It lets you scan the hosts file for errors, duplicates, and possible hijacks – and also lets you create an Exclusion list. One more useful feature it offers is the Hosts file backup manager. Backup your Hosts file to a safe place and use it to restore it, should the need arise.
Hostman also lets you Flush DNS cache, open Hosts with a text editor, count the number of hosts, find duplicates, replace IP, scan hosts for malicious entries, rearrange hosts, manage DNS Client Service and more. In short, its the only Hosts Manager that you will even need. You can download it from its home page. SysMate Hosts File Manager is another tool that lets you do so.
How to manually reset Hosts file back to default in Windows may also interest you.
If your browser has been hijacked, you might find this post on Browser Hijacking and Free Browser Hijacker Removal Tools helpful.
Date: December 23, 2018 Tags: Hosts, Security
Где находится файл hosts и как его изменить
Файл hosts — текстовый документ, который содержит в себе информацию о домене и адресе, на который ссылается домен.досту Файл hosts появился во времена зарождения Интернета (ARPANET) и служил где лежит неким маршрутизатором, пока на замену ему не пришла служба DNS. Но до сих пор он не утратил важности и по-прежнему используется как инструмент, который обладает приоритетом перед обращением к DNS-серверам.
Зачем нужен файл hosts
Предположим: вы зарегистрировали домен и привязали его к Hosting Linux. Но чтобы увидеть сайт, вам нужно дождаться делегирования домена на DNS-серверы. В файле hosts вы можете указать ваш домен и IP-адрес хостинга, а затем открыть браузер и зайти на ваш сайт, не дожидаясь делегирования домена. Также с его помощью вы можете заблокировать на локальном компьютере доступ к определённому сайту, указав соответствующую запись.
Где находится файл hosts
Путь к папке, где лежит файл hosts, зависит от операционной системы, которая установлена на вашем компьютере:
Windows XP, 2003, Vista, 7, 8, 10 — c:\windows\system32\drivers\etc\hosts
Linux, Ubuntu, Unix, BSD — /etc/hosts
Редактировать файл etc hosts нужно от имени администратора, иначе вы не сможете сохранить внесённые изменения.
Как внести изменения в файл hosts
Ниже мы рассмотрим, как редактировать и как сохранить файл hosts. Важно открыть файл с правами администратора, иначе система не даст вам его сохранить. Выберите вашу операционную систему и следуйте инструкции:
Запустите Блокнот или любой другой редактор от имени администратора. Откройте Пуск, найдите нужный редактор, нажмите по нему правой кнопкой мыши и выберите Запуск от имени администратора:
Как отредактировать файл hosts
В меню «Файл» нажмите Открыть и перейдите в каталог, в котором расположен файл hosts. Измените тип файла на «Все файлы»:
Добавьте в конце файла необходимую запись в формате:
123.123.123.123 | faq-reg.ru | www.faq-reg.ru |
123.123.123.123 — IP-адрес вашего сервера или хостинга,
faq-reg.ru — имя вашего домена.
Теперь вы можете открыть ваш сайт в браузере, не дожидаясь обновления DNS-серверов.
Чтобы изменить файл hosts в виндовс 10 (8), выполните следующие действия:
Запустите Блокнот или любой другой редактор от имени администратора. Для этого найдите его в Пуске, нажмите по нему правой кнопкой мыши и выберите Запуск от имени администратора:
В меню «Файл» нажмите Открыть и перейдите в каталог, где находится файл hosts . Измените тип файла на «Все файлы»:
Добавьте в конце файла необходимую запись в формате:
123.123.123.123 | faq-reg.ru | www.faq-reg.ru |
123.123.123.123 — IP-адрес вашего сервера или хостинга,
faq-reg.ru — имя вашего домена.
Теперь вы можете открыть ваш сайт в браузере, не дожидаясь обновления DNS-серверов.
В Linux файл hosts находится в папке etc. Чтобы отредактировать его:
Введите в терминал linux команду hosts: sudo nano /etc/hosts
Добавьте в конце файла необходимую запись в формате:
123.123.123.123 | faq-reg.ru | www.faq-reg.ru |
123.123.123.123 — IP-адрес вашего сервера или хостинга,
faq-reg.ru — имя вашего домена.
Теперь вы можете открыть ваш сайт в браузере, не дожидаясь обновления DNS-серверов.
Файл hosts в Ubuntu редактируется так же, как и во всех Unix-системах.
Файл hosts в Mac OS расположен в каталоге: /private/etc/hosts. Чтобы изменить его:
Введите команду: sudo nano /etc/hosts и нажмите Enter:
Добавьте в конце файла необходимую запись в формате:
123.123.123.123 | faq-reg.ru | www.faq-reg.ru |
123.123.123.123 — IP-адрес вашего сервера или хостинга,
faq-reg.ru — имя вашего домена.
Теперь вы можете открыть ваш сайт в браузере, не дожидаясь обновления DNS-серверов.
Также вы можете заблокировать определенный сайт через файл hosts, воспользовавшись инструкцией ниже:
Блокировка доступа к сайту через файл hosts
Доступ к сайту также можно ограничить для локального компьютера. Для этого укажите адрес страницы (домен) в файле hosts. Заблокировать IP нежелательного сайта не требуется. Блокировка осуществляется по локальному хосту с фиксированным IP (127.0.0.1):
В указанной на скриншоте строке укажите IP-адрес 127.0.0.1 и через пробел адрес нежелательного сайта. Чтобы заблокировать несколько сайтов, повторите действие в следующей строке. В примере ниже в файле hosts отказано в доступе (заблокирован доступ) к сайтам «vk.com» и «youtube.com»:
Готово! Доступ к сайтам будет ограничен на определенном ПК.
Оригинальный файл hosts и как его восстановить
Скачать оригинал файла hosts можно на разных ресурсах. Но мы не рекомендуем делать это, так как файл может быть заражен.
Файл hosts по умолчанию есть в каждой операционной системе, но он может быть скрыт для просмотра. Следуя инструкциям выше, вы сможете его открыть и отредактировать. Если вы удалили его, то просто создайте текстовый файл без расширения в нужной папке.
По умолчанию файл hosts выглядит следующим образом:
How to Edit the Hosts File in Windows
Can be useful for anyone in IT
The hosts file is a text-based file located in the same place in all modern Windows versions. Most people don’t ever need to get into it, but if you do, you’ll need to know how to open and edit the hosts file.
However, in some versions of Windows, editing the hosts file directly isn’t allowed. In fact, you’ll get an error if you try to save the changes. Fortunately, there’s a simple tip you can use to edit the hosts file in Windows 10, 8, 7, Vista, or XP.
What Does The Hosts File Do?
The purpose of the hosts file was originally to be what DNS servers do now – map friendly domain names to unfriendly IP addresses.
It’s much easier to remember a domain name like YouTube.com than an IP address like 172.217.1.238. Instead of having to type the IP address into the address bar each time you want to watch YouTube videos, you can just enter the domain name, and the DNS server your device is using will map the name to the right address so you can get to the webpage a lot easier.
The hosts file, since it serves as a sort of DNS server, works the same way. You can enter an IP address that a domain name should be resolved to. In other words, you could order your computer to load a different IP address than the DNS server would, essentially letting you do a few cool things.
Why Edit The Hosts File?
One reason to edit the hosts file is if you want a super basic way to block websites from loading on your computer. Enter an invalid or wrong IP address for the site you want to block, and each time you try accessing it, the hosts file will load the IP address you chose. Depending on what you picked, it might completely block the website.
You can use the same technique to make the hosts file block malicious sites. There are even lists of hosts file entries (such as this one) you can download and import into your hosts file to block hundreds of malicious sites or ads.
Another use for the hosts file is to speed up your web browsing. If the DNS server you’re using is down or not working quickly enough, manually entering the IP address and domain name mappings in your hosts file lets your computer find those addresses nearly instantly instead of relying on the DNS server.
Tip: Learn how to use alternate DNS servers to get faster internet access.
Windows Hosts File Location
You need to know where to go to find the hosts file before you can open it for editing. This is the hosts file location in Windows 10 through Windows XP:
C:\Windows\system32\drivers\etc
How To Edit The Hosts File
The hosts file is a text file, meaning that you need a text editor to make changes to it. However, since the hosts file is super basic and doesn’t need to deal with hyperlinks, images, etc., you can use a basic text editor (i.e., there’s no need to use a full-fledged editor like Microsoft Word).
Opening The Hosts File
Let’s start with simply opening the hosts file. We’ll use Notepad, which is built into Windows 10 down through Windows XP.
- Open the Run dialog box by holding down the Windows key and then pressing R once.
- Type notepad and then press Enter to open the program.
- Go to File >Open.
- In the file name text box at the bottom, type (or copy and paste) the hosts file location shown above and then press Enter.
- Select the menu to the right of the text box to change Text Documents (*.txt) to All Files (*).
- Double-click hosts from the list of files to open the hosts file for editing in Notepad.
Editing The Hosts File
There are a few examples in the hosts file to show you how to format your entries. You have to put the IP address first followed by the domain name, and the two have to be separated by at least one space (a tab is a good way to format them).
Here are some examples:
127.0.0.1 www.google.com
13.249.79.104 www.bing.com
As you can see in the image above and read from the directions in the hosts file, the # symbol is used as a comment, meaning that anything that follows it is avoided. This is why the two example lines we give above are useful in this hosts file; they’re not being followed by that symbol.
If you want to block websites with the hosts file, such as YouTube, Amazon, Google, Reddit.com, etc., you can enter a false IP address like 0.0.0.0.
Note: When you enter the URL of the site you want to associate with a specific IP address, be sure to exclude the beginning part and only type the subdomain, such as www or whatever it happens to be for the site you’re adding.
Saving The Hosts File
Here’s how we’ll save the hosts file to make sure it works no matter which operating system you use, which text editor you picked, or how your Windows settings are configured:
- Go to File >Save As.
- Change the Save as type option to All Files (*).
- Rename the file to hosts.backupfile, and then save it to your desktop.
- Close Notepad and then find the hosts file you just created on the desktop. You want to delete the .backupfile part of the name and leave only hosts (with no period or text after the word).
- After you do that, click away from the file to something else on the desktop, and confirm the name change when asked.
- Copy the hosts file.
- Open the hosts file location you had open before (the etc folder).
- Paste the hosts file you copied from the desktop, and confirm any overwrite prompts if you see them.
Founder of Help Desk Geek and managing editor. He began blogging in 2007 and quit his job in 2010 to blog full-time. He has over 15 years of industry experience in IT and holds several technical certifications. Read Aseem’s Full Bio