При соединении с каким-либо сайтом, прежде чем запросить его IP у DNS-сервера, Windows проверяет файл hosts: если для каких-то сайтов в этом файле заданы IP-адреса, используются именно они. Это может использоваться для блокировки доступа к некоторым сайтам (и некоторые вирусы блокируют доступ к сайтам антивирусов) и других задач.
В этой инструкции пошагово о том, где находится файл hosts в Windows 11, как его отредактировать и как выглядит файл hosts по умолчанию.
Где находится файл hosts в Windows 11
Расположение файла hosts одинаково во всех версиях Windows: он находится в папке C:\Windows\system32\drivers\etc
Иногда в указанной папке можно обнаружить более одного файла с именем hosts, в этом случае нужный — тот, который не имеет никакого расширения.
Дополнительные нюансы, касающиеся файла hosts:
- Иногда его может и не быть в указанной папке. Если вы столкнулись с таким, это странно, но никак не влияет на работу вашего Интернет-подключения (по умолчанию файл hosts не содержит значимых записей).
- Теоретически возможно изменение расположения файла hosts. Оно прописывается в разделе реестра
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\
в параметре DataBasePath. На изображении ниже — значение этого параметра по умолчанию.
Как изменить файл hosts
Если вам требуется отредактировать файл hosts, сделать это можно в любом текстовом редакторе, но его обязательно следует запускать от имени администратора. Пример изменения файла hosts с помощью блокнота в Windows 11:
- С помощью поиска на панели задач найдите «Блокнот», нажмите по найденному результату правой кнопкой мыши и выберите пункт «Запуск от имени администратора».
- После запуска в меню блокнота выберите «Файл» — «Открыть», а затем в поле внизу слева выберите «Все файлы».
- Перейдите к папке C:\Windows\system32\drivers\etc и откройте файл hosts без расширения.
- По умолчанию файл hosts может иметь вид либо как на скриншоте ниже, либо быть пустым — оба варианта равнозначны, поскольку все строки, начинающиеся с символа решётки являются комментариями и не участвуют в работе этого файла.
- Для добавления записей, добавьте их на новой строке: сначала IP-адрес, а затем через пробел — сайт, при открытии которого будет открываться указанный IP-адрес. Например, если вы хотите заблокировать сайт Одноклассники, вы можете добавить новую строку 0.0.0.0 ok.ru (для блокировки обычно используются IP-адреса 127.0.0.1 или 0.0.0.0, но второй вариант предпочтительнее, так как при некоторых условиях на первом адресе может открываться HTTP-ресурс, запущенный на текущем компьютере).
- После завершения редактирования, в меню выберите Файл — Сохранить. Каких-либо окон для выбора места сохранения появиться не должно, а если появились, это говорит о том, что вы запустили блокнот не от имени администратора и сохранить файл hosts «правильно» не получится.
Восстановление файла hosts по умолчанию
Если в вашем файле hosts появились блокировки каких-то нужных сайтов (антивирусов, компьютерных или других), то для его восстановления вам достаточно выполнить описанные выше 1–3, а затем либо удалить всё содержимое файла, либо, если вам требуется первозданный файл hosts — скопировать и вставить следующее содержимое:
# Copyright (c) 1993-2009 Microsoft Corp. # # This is a sample HOSTS file used by Microsoft TCP/IP for Windows. # # This file contains the mappings of IP addresses to host names. Each # entry should be kept on an individual line. The IP address should # be placed in the first column followed by the corresponding host name. # The IP address and the host name should be separated by at least one # space. # # Additionally, comments (such as these) may be inserted on individual # lines or following the machine name denoted by a '#' symbol. # # For example: # # 102.54.94.97 rhino.acme.com # source server # 38.25.63.10 x.acme.com # x client host # localhost name resolution is handled within DNS itself. # 127.0.0.1 localhost # ::1 localhost
После удаления строк или вставки содержимого файла hosts, сохраните его (Файл — Сохранить). Как и в предыдущем случае, если при сохранении появилось окно выбора места сохранения, это говорит о том, что текстовый редактор был запущен не от имени администратора.
Также вы можете использовать сторонние средства удаления вредоносных программ, которые, помимо прочего, умеют восстанавливать файл hosts.
Например, если перед сканированием AdwCleaner зайти в «Параметры» и включить опцию «Сбросить файлы Hosts», то в ходе сканирования и последующей очистки компьютера будет сброшен и этот файл.
Если изменения, сделанные в файле hosts не работают
Как правило, все внесённые в файл hosts изменения начинают работать сразу после его сохранения, какая-либо перезагрузка не требуется. Однако, в некоторых случаях это может быть не так. Здесь могут помочь следующие действия:
- Если вы убирали блокировку сайтов в файле hosts, а они все равно заблокированы, возможно, блокировка присутствует где-то ещё, например, в брандмауэре Windows.
- Если вы блокировали сайт, а он продолжает открываться, причиной может быть тот факт, что многие современные браузеры начали использовать DNS over HTTPS и блокировка не заработает, пока вы не включите DNS over HTTPS в Windows 11.
- Неверный синтаксис в строках hosts также может приводить к неработоспособности записей. В начале строки не требуются пробелы или символы решётки. Между IP-адресом и доменом используйте один символ пробела, допускается использование табуляции. Кодировка файла — ANSI или UTF-8 (блокнот по умолчанию сохранит в правильной кодировке).
- Использование прокси и некоторых VPN-сервисов также может повлиять на работу файла hosts.
The hosts file is a critical component of the Windows operating system, responsible for mapping hostnames to IP addresses. By modifying the hosts file, you can block websites, redirect URLs, or customize your network environment for development purposes. However, editing the hosts file requires administrative privileges to ensure that unauthorized changes don’t compromise the integrity and security of the system. In Windows 11, the process of opening and editing the hosts file as an administrator is straightforward, yet it’s essential to approach it with caution.
In this article, we’ll explore in detail how to access and modify the hosts file on a Windows 11 system while providing you the context and steps necessary to do so safely.
Understanding the Hosts File
Before diving into the steps, it’s essential to grasp the purpose of the hosts file:
-
Definition: The hosts file is a plain text file located in the system32driversetc directory. It translates human-readable domain names to IP addresses, much like DNS but at a local level.
-
Usage Scenarios:
- Blocking Websites: By redirecting a website address to
127.0.0.1
, you can prevent access to that site. - Local Development: Developers often use it to link domain names to local IP addresses while testing applications locally.
- Temporary Fixes: Sometimes, websites may go down or change IP addresses, and you can use the hosts file to maintain access until the issue is resolved.
- Blocking Websites: By redirecting a website address to
Accessing the Hosts File in Windows 11
To modify the hosts file, you need to open it with administrative rights. Here’s how you can do that in a step-by-step manner:
Step 1: Open Notepad as Administrator
Since the hosts file is a text file, you can use Notepad (or any other text editor) to open and edit it. However, you must ensure that you run Notepad with administrative rights.
-
Locate Notepad:
- Click on the Start button or press the Windows key on your keyboard.
- Type “Notepad” in the search bar.
-
Run as Administrator:
- Right-click on the Notepad app from the search results.
- Select Run as administrator. If prompted by User Account Control (UAC), click Yes to allow changes.
Step 2: Open the Hosts File in Notepad
With Notepad running in administrative mode, now you can access the hosts file.
-
Open the Hosts File:
- In Notepad, click on File in the top-left corner.
- Choose Open.
- Navigate to the following path:
C:WindowsSystem32driversetc
- Ensure that you change the file type filter in the bottom-right corner from «Text Documents (.txt)» to «All Files (.*)».
-
Select the Hosts File:
- Locate the hosts file and click on it.
- Click Open.
At this point, the hosts file is now open in Notepad, and you can start making necessary edits.
Editing the Hosts File
Understanding the Initial Content
When you open the hosts file, you will see some default entries. Here’s what they usually look like:
# This file is used by the Microsoft TCP/IP for Windows.
# It contains the mappings of IP addresses to host names.
# Each entry should be kept on an individual line.
# The IP address should be placed in the first column followed by the corresponding host name.
# For example:
# 127.0.0.1 localhost
# ::1 localhost
These comments explain how to structure the entries. A typical entry would look like this:
Adding New Entries
To add a new entry:
- Navigate to a new line: After the existing contents, move to the next line.
-
Write your entry: For instance, if you wanted to block «example.com,» you would type:
127.0.0.1 example.com
- Save your changes: Once your edits are complete, go to File > Save or press
Ctrl + S
, then close Notepad.
IMPORTANT: Backup the Hosts File
Before making any changes, it’s wise to create a backup of the original hosts file in case you need to revert:
- Open File Explorer and navigate to
C:WindowsSystem32driversetc
. - Right-click on the hosts file and select Copy.
- Right-click in the same folder (or another designated location) and select Paste. You can rename this copy (for example,
hosts_backup
).
Common Issues When Editing the Hosts File
Sometimes, users may encounter issues when attempting to edit the hosts file. Here are a few common problems and their solutions:
Permission Denied
If you are unable to save changes:
- Ensure you opened Notepad with administrative rights as outlined earlier.
- Confirm that your user account has administrative privileges.
Changes Not Taking Effect
If you notice no changes after edits:
- Clear DNS Cache: Run Command Prompt as administrator and execute the command:
ipconfig /flushdns
- Check File Format: Ensure the file is saved as plain text with no additional extensions (like
.txt
).
Accessing the Hosts File with Command Prompt
Alternatively, you can directly open the hosts file using the Command Prompt:
-
Open Command Prompt as Administrator:
- Type «cmd» in the Start menu.
- Right-click on Command Prompt and choose Run as administrator.
-
Open the Hosts File:
- Use the command:
notepad C:WindowsSystem32driversetchosts
- This will launch Notepad with the hosts file directly.
- Use the command:
Further Modifications and Advanced Usage
Blocking Multiple Websites
You can block multiple websites by adding new lines for each:
127.0.0.1 example.com
127.0.0.1 another-example.com
Redirecting URLs
You can redirect a URL to another IP as follows:
192.168.1.10 my-local-site.com
This is particularly useful for local development environments.
Removing Entries
To remove an entry, simply find the line you wish to delete and remove it entirely, then save the file.
Verifying Your Changes
To ensure your changes were successful, you can check by:
- Opening a web browser.
- Typing the website URL you modified or added.
- If it is blocked or redirected as intended, your changes are successful.
Conclusion
Editing the hosts file in Windows 11 can be an effective way to block websites or redirect traffic for testing environments. By following the steps outlined in this article, you can open the hosts file as an Administrator, make your modifications, and troubleshoot common issues. Remember always to back up the original hosts file before making changes, and only modify it if you understand the implications of your changes.
Best Practices for Using the Hosts File
- Be Careful: Only modify entries you are sure about. Improper changes can affect your internet access.
- Document Changes: Keep a record of any changes you make, making it easier to revert if necessary.
- Revert if Needed: If issues arise after changes, revert to the backups you made.
With these practices in mind, you can efficiently manage the hosts file on your Windows 11 system and effectively control your network traffic at a local level.
Hosts file is a local file available as part of an operating system and used to map IP addresses corresponding to domain names. The browser then resolves the entered domain name into an IP address found in the hosts file before using browser’s DNS settings. In this article, we will explain how to edit hosts file in Windows 11 PC. Also, learn more on how to edit hosts file in macOS.
There are two major reasons for users to modify hosts file.
- Eliminate the resolving host time through normal DNS resolution.
- Block certain domains by pointing it to localhost IP address.
In both cases you need to create additional entries in hosts file as explained in the below sections.
Step 1 – Open Notepad in Administrator Mode
Click the “Start” icon in Taskbar and then click the search box. Alternatively, use Windows Search and type “notepad” in the search box. From the search result, right-click on the app and select “Run as administrator” option.
Step 2 – Open Hosts File
Once Notepad is opened in administrator mode, go to “File > Open” from the menu or press “Control + O” shortcut keys.
Hosts file in Windows 11 is stored in the location “C:/Windows/System32/drivers/etc/”. Simply, copy and paste this path in the address bar and press enter to go to that location. By default, you will not see any files in that location. Now, select “All Files” from the “File name” dropdown and then you will see a list of files. Select hosts file and click on “Open” button to view its content.
Step 3 – Edit Hosts File in Windows 11
The hosts file will open in Notepad app and add required entries at the end. Press “Control + S” or go to “File > Save” menu to save your changes.
Basics Rules in Modifying Hosts File
Remember the following things when adding entries in your hosts file:
- By default, tab is used to separate IP and domain in the sample entries in your hosts file. However, you can use a single space between IP and domain name for new entries.
- Add each set of IP and domain in a separate line.
- Add domain and subdomains separately. For example, webnots.com, tools.webnots.com and blog.webnots.com needs to be added as three separate lines though IP address could be same or different.
- Use # to add comments in the hosts file.
- Hosts file does not have any extension, hence ensure to save the file as “All Files” type and not as a text document with .txt extension.
- After editing the hosts file, restart your computer for the changes to take effect.
Step 4 – Blocking Sites Using Hosts File
Besides resolving the host name, you can also use the hosts file to block sites by pointing the domain to localhost IP address. For example, add the following entry to block facebook.com when you open the site in a browser.
127.0.0.1 facebook.com
::1 facebook.com
Here, 127.0.0.1 and ::1 are the IP addresses of the localhost for IPv4 and IPv6 respectively.
- To edit the “Hosts” files on Windows, open PowerToys > Host editor, and click “Launch Hosts File Editor,” “Accept,” and “New entry.” Then, create the entry with IP address, hostname, and comment, turn on the “Active” option, and click “Add.”
- To edit the “Hosts” file from Notepad (admin), open File > Open, and browse to the “C:\Windows\System32\Drivers\etc” location and open the “hosts” file. Add a new IP address and domain mapping – for example, 127.0.0.1 domain.com.
- If you can’t edit the Hosts file, it’s because you need administrative permissions on Windows 11.
On Windows 11 (and 10), you can edit the “Hosts” file to manually override the system’s Domain Name System (DNS) settings for a specific internet domain (website) or device connected to the local network.
Usually, you don’t have to worry about manually mapping an IP address to a domain name using the Hosts file located in the C:\Windows\System32\Drivers\etc
path on Windows 11. (It’s the same path on Windows 10.) However, it can come in handy in many scenarios. For instance, when you want to block certain websites. When you don’t have a local DNS server in the network, you must map an IP address to a computer name or prepare a website transfer to a new hosting provider.
Regardless of your reason, Windows 11 and Windows 10 make it super simple to edit the Hosts file using Notepad or any other text editor as long as you open the app as an administrator. Otherwise, you won’t be able to edit the file. In addition, the PowerToys app includes a tool that makes it easier to manage entries in the Hosts file. Alternatively, you can also use Command Prompt to edit the Hosts file.
In this guide, you will learn the steps to modify the Hosts files on Windows (11 and 10) to map host names to IP addresses.
- Edit Hosts file on Windows from PowerToys
- Edit Hosts file on Windows from Notepad
- Edit Hosts file on Windows from Command Prompt
Edit Hosts file on Windows from PowerToys
To edit the Hosts files with the PowerToys editor, use these steps:
-
Open PowerToys.
-
Click on Advanced.
-
Click on Hosts File Editor.
-
Under the “Activation” section, click the “Launch Hosts File Editor” option.
-
Click the Accept button for the warning.
-
Click the New entry button.
-
Confirm the IP address, hostname, and comment (as necessary).
-
Turn on the Active button.
-
Click the Add button.
- (Optional) Right-click the entry and choose the “Delete” option for a specific configuration.
After you complete the steps, the Hosts file will save with the new entries, and you should now be able to test the new configuration. In the editor, you can enable or disable entries with a toggle switch.
Edit Hosts file on Windows from Notepad
To edit the “Hosts” file on Windows with Notepad, use these steps:
-
Open Start.
-
Search for Notepad, right-click the top result, and select the Run as administrator option.
-
Click on File and select the Open option.
-
Browse to the Hosts file location:
C:\Windows\System32\Drivers\etc\
-
Use the drop-down menu next to “File name” and select the “All Files” option.
-
Select the Hosts file.
-
Click the Open button.
-
In a new line, enter the IP address of the remote server, add at least one space, and confirm the domain name or computer name to reach the service. For example,
159.223.126.251 google.com #This PC redirects Google.com to the specified IP address
.Quick note: If you want to add another entry, use a new line and don’t use the pound sign (#) since that symbol is only used for commenting.
-
(Optional) Delete the entire line to remove the entry from the Hosts file.
-
Click on File.
-
Select the Save option.
Once you complete the steps, you can test the changes by opening Command Prompt and using the ping command to ensure the host is reachable.
If you want to block your computer from accessing certain websites, you can use the loopback address (127.0.0.1) followed by the domain name (127.0.0.1 website.com). Also, if you can edit the “Hosts” file on Windows 11, it’s because you need administrative permissions.
Edit Hosts file on Windows from Command Prompt
To edit the “Hosts” file through Command Prompt, use these steps:
-
Open Start.
-
Search for Command Prompt, right-click the top result, and select the Run as administrator option.
-
Type the following command to add another entry to the Hosts file and press Enter:
echo 159.223.126.251 google.com >> %SystemRoot%\System32\drivers\etc\hosts
In the command, replace “159.223.126.251 google.com” for the entry you want to include in the file.
-
(Optional) Type the following command to confirm the changes and press Enter:
type %SystemRoot%\System32\drivers\etc\hosts
After you complete the steps, the entry will be added to Hosts file.
Since the Hosts file is a text file, if you want to remove an entry, the easiest way to complete this configuration from Command Prompt is to run the notepad %SystemRoot%\System32\drivers\etc\hosts
command to open the file and delete the line to remove the entry and save the file.
Update April 22, 2024: This guide has been updated to ensure accuracy and reflect changes to the process using Command Prompt.
В этой статье мы расскажем, что такое файл hosts и где он лежит.
hosts — это текстовый документ, в котором прописаны соответствия доменов IP-адресам. Когда вы вводите домен в адресной строке браузера, в первую очередь запрос IP-адреса отправляется к файлу hosts. Если в нем не прописана информация об искомом сайте, запрос перенаправляется к системе DNS.
Как выглядит файл hosts в Windows:
Как выглядит файл hosts в Linux:
Как появился файл hosts
В 1970-х годах появилась прародительница современного интернета: сеть под названием ARPAnet. Она состояла из нескольких сотен порталов с информацией. За маршрутизацию в этой сети отвечал файл hosts.txt: в нем хранились соответствия между именем ресурса и его IP-адресом.
В то время за hosts.txt отвечал Сетевой информационный центр Стэнфордского исследовательского института (сокращенно NIC SRI). Если в сети появился новый сайт, администраторы отправляли информацию об изменениях в NIC SRI. После этого они синхронизировали свой файл hosts с данными из NIC. Это происходило 1-2 раза в неделю.
Однако по мере распространения интернета эта схема работы стала невозможна: объем информации рос, и синхронизировать данные стало значительно сложнее.
В 1984 году появились документы, в которых была описана система DNS. Именно она пришла на замену hosts.txt.
Файл hosts по-прежнему существует, но его назначение изменилось. Он есть на каждом компьютере и отвечает за отображение сайтов на конкретном устройстве. На глобальную паутину hosts не влияет.
Как можно использовать файл hosts
Файл hosts можно использовать для проверки работы сайта: это полезно, если вы недавно зарегистрировали новый домен или изменили DNS-серверы для существующего. Обновление DNS происходит в течение 24 часов, однако hosts позволяет увидеть сайт раньше. Для этого в нем нужно прописать доменное имя и IP-адрес хоста.
Что такое хост? Это сервер или услуга, на которой размещен ваш сайт. Уточнить ее IP-адрес можно у поставщика услуг.
Где находится файл hosts
Расположение файла hosts зависит от семейства и версии ОС, которая установлена на вашем компьютере.
- Путь к файлу hosts на Windows 10: c:\windows\system32\drivers\etc\hosts
- Путь к файлу hosts на Windows 11: c:\windows\system32\drivers\etc\hosts
- Путь к файлу hosts на Windows 7: c:\windows\system32\drivers\etc\hosts
- Путь к файлу hosts на Linux: /etc/hosts
- Путь к файлу hosts на macOS: /private/etc/hosts
Не удается изменить файл hosts: как это исправить
Иногда попытка изменить hosts завершается ошибкой. С этим можно столкнуться, если вы редактируете файл в системе Windows.
Чтобы решить эту проблему, откройте Блокнот от имени администратора. Для этого:
- Кликните по строке поиска. Нажмите на Блокнот правой кнопкой мыши и выберите Запуск от имени администратора:
- Нажмите на меню Файл и выберите Открыть.
- Выберите файл hosts на вашем компьютере и нажмите Открыть.
- Добавьте данные о вашем сайте. В примере:
123.123.123.123 — IP-адрес вашего хостинга,
sweb.ru — доменное имя вашего сайта. - Затем нажмите Файл и выберите Сохранить
Что такое localhost
localhost — это домен, который позволяет обратиться к вашему компьютеру напрямую. Это имя привязано к IP-адресу 127.0.0.1.
Как правило, localhost используется для настройки сетевых инструментов: например, если вы настроили сервер на компьютере и хотите к нему обратиться по имени или IP.
Помимо этого, localhost можно использовать, чтобы закрыть доступ к какому-либо сайту. Предположим, вы хотите заблокировать vk.com на конкретном компьютере. Тогда в файл hosts необходимо добавить строку:
127.0.0.1 vk.com
Как восстановить оригинальный файл hosts
Если вы случайно удалили файл hosts, его можно восстановить вручную. Для этого перейдите в папку, в которой он должен храниться. Затем создайте текстовый файл без расширения, назовите его hosts. После этого файл необходимо наполнить. Содержимое по умолчанию зависит от ОС, которая установлена на вашем компьютере.
Стандартный hosts для Windows:
# Copyright (c) 1993-2006 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com
# x client host
# localhost name resolution is handle within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
Стандартный hosts для Linux:
127.0.0.1 localhost
127.0.1.1 username
# 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
Вместо username укажите имя вашей учетной записи на компьютере.
Стандартный hosts для MacOS:
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
После этого сохраните файл.
Несмотря на то, что файл hosts уже не влияет на работу сайтов в глобальной сети, он помогает решить некоторые важные задачи на вашем компьютере.