How to Edit Hosts File in Windows, MacOS and Linux
As we all know, the DNS (Domain Name System) is the internet’s phone book. However, did you know that your computer’s hosts file can also be used as a domain name directory? This article will explain what the hosts file is and how to edit it in Windows 10, Linux, and Mac to simulate DNS changes.

What is a Hosts File
A hosts file is a local file that contains domain names and their matching IP addresses. It’s found in all common operating systems and acts as a map, identifying and locating hosts on IP networks.
When you visit a website, your computer first checks the hosts file to see which IP address it connects to. If the information is not present, your internet service provider will search the DNS for the resources needed to load the site.
Why Modify the Hosts File
You can take advantage of the situation above when you’ve just purchased a domain. Or, when you’re migrating your website to a different hosting provider and your domain needs to point to the new server. Usually, it’ll take 24 to 48 hours for your domain to start working, and during that time, you won’t be able to access your site.
By editing the hosts file, specifically adding a custom IP address that points to your domain, you’ll be able to open your website. This is useful if you want to modify your site after migrating and see how it’ll look on the new server.
The hosts file is written in plain-text format. Hence, you can use any text editor like Notepad, for example, to edit it.
However, do keep in mind that the changes will only affect the system that the hosts file is in.
How to Edit Hosts File in Windows 10
Before we begin, you’ll need an IP address for your domain:
- Login to your hPanel, then on the left sidebar navigate to Hosting -> Plan Details -> Website IP address.
- Copy the IP address:

Now let’s edit the hosts file. There are two methods for Windows 10 – manually or using the Hosts File Editor tool. Generally, you can use the guides below in any version of Windows.
Change the File Manually
- Press Start and find Notepad. Right-click to Run as administrator.

- Once in Notepad, go to File -> Open. Get to C:\Windows\System32\Drivers\etc and make sure to select All Files to find the hosts file.

- Now you can edit the hosts file. Add the custom IP address you’ve made earlier, followed by a space, then your domain name.

- When you’re finished, don’t forget to save your changes.
Using Hosts File Editor Tool
There’s an easier way to edit the hosts file in Windows 10, and that’s by using the Hosts File Editor.

- Once you’re in the Hosts File Editor, fill your targeted IP address and the domain name under their columns.
- Save your changes.
How to Edit Hosts File in Linux
In Linux, you can use your favorite text editor to do the job. Here, we will use Gedit in Ubuntu. Open the Terminal by pressing Ctrl+Alt+T.

-
Type the command below, then key in your admin password:
How to Edit Hosts File in macOS
If you’re running macOS from Leopard (10.6) to its latest version, follow these steps to edit the Mac hosts file:
- Click on the Launchpad and open Terminal.
- We’ll be using the Nano Editor. To run it as an administrator, insert the statement below, and press Enter:
- Type in your password. You’ll be directed to the hosts file.
- Add your chosen IP address, followed by the domain name, separated by a space.
- Make sure to save your changes using the Ctrl + O shortcut.
For more detailed steps on editing the hosts file on MacOS, check out our guide.
Conclusion
You’ve just learned how to edit the hosts file on three different operating systems.
However, do keep in mind that these changes require administrative rights on every system, and it will only take effect on the computer that the hosts file is in.
Here’s a quick recap:
- Windows 10 ‒ use any text editor, like Notepad, to modify the file or use the Hosts File Editor.
- Linux ‒ use either Gedit or any other text editor you prefer.
- Mac ‒ resort to the Nano Editor via the Terminal.
Elvinas is a senior server administrator at Hostinger. He monitors the infrastructure’s well-being and keeps the uptime at a maximum. Besides server management, web development has always been one of his biggest passions.
Как изменить файл hosts
В некоторых ситуациях может потребоваться изменить файл hosts в Windows 10, 8.1 или Windows 7. Иногда причина тому — вирусы и вредоносные программы, вносящие изменения в hosts, из-за чего не получается зайти на определенные сайты, а иногда вы и сами можете захотеть отредактировать этот файл для того, чтобы ограничить доступ к какому-либо сайту.
В этой инструкции подробно о том, как изменить hosts в Windows, о способах исправить этот файл и вернуть его к первоначальному состоянию встроенными средствами системы и с помощью сторонних программ, а также некоторые дополнительные нюансы, которые могут быть полезны.
Изменение файла hosts в блокноте
Содержимое файла hosts представляет собой набор записей из IP-адреса и URL. Например, строка «127.0.0.1 vk.com» (без кавычек) будет означать, что при открытии в браузере адреса vk.com, будет открываться не настоящий IP-адрес ВК, а указанный адрес из файла hosts. Все строки файла hosts, начинающиеся со значка решетки являются комментариями, т.е. их содержимое, изменение или удаление никак не влияет на работу.
Самый простой способ редактирования файла hosts — использовать встроенный текстовый редактор «Блокнот». Самый важны момент, который нужно учесть: текстовый редактор должен запускаться от имени администратора, в противном случае вы не сможете сохранить сделанные изменения. Отдельно опишу как проделать необходимое в разных версиях Windows, хотя по своей сути шаги отличаться не будут.
Как изменить hosts в Windows 10 с помощью блокнота
Для редактирования файла hosts в Windows 10 используйте следующие простые шаги:

- Начните вводить «Блокнот» в поле поиска на панели задач. Когда нужный результат будет найден, нажмите по нему правой кнопкой мыши и выберите пункт «Запуск от имени администратора».
- В меню блокнота выберите Файл — Открыть и укажите путь к файлу hosts в папке C:\Windows\System32\drivers\etc. Если в этой папке присутствует несколько файлов с таким именем, открывайте тот, который не имеет никакого расширения.
- Внесите необходимые изменения в файл hosts, добавьте или удалите строки соответствий IP и URL, после чего сохраните файл через меню.
Готово, файл отредактирован. Изменения могут вступить в действия не сразу, а только после перезагрузки компьютера. Более подробно о том, что и как можно изменить в инструкции: Как редактировать или исправить файл hosts в Windows 10.
Редактирование hosts в Windows 8.1 или 8
Для запуска блокнота от имени Администратора в Windows 8.1 и 8 находясь на начальном экране с плитками, начните набирать слово «Блокнот», когда он появится в поиске, кликните по нему правой кнопкой мыши и выберите «Запуск от имени администратора».

В блокноте нажмите «Файл» — «Открыть», после чего справа от «Имя файла» вместо «Текстовые документы» выберите пункт «Все файлы» (в противном случае, зайдя в нужную папку вы увидите «Нет элементов, удовлетворяющих условиям поиска») и после этого откройте файл hosts, который находится в папке C:\Windows\System32\drivers\etc.

Может оказаться, что в этой папке не один, а два hosts или даже больше. Открывать следует тот, который не имеет никакого расширения.

По умолчанию, данный файл в Windows выглядит как на картинке выше (кроме последней строчки). В верхней части — комментарии о том, для чего нужен этот файл (могут быть и на русском, это не важно), а в нижней мы можем добавлять необходимые строчки. Первая часть означает адрес, на который будут перенаправляться запросы, а вторая — какие именно запросы.
Например, если мы добавим в файл hosts строчку 127.0.0.1 odnoklassniki.ru, то у нас не будут открываться одноклассники (адрес 127.0.0.1 зарезервирован системой за локальным компьютером и если у вас на нем не запущен http сервер, то ничего не откроется, а можно ввести 0.0.0.0, тогда сайт точно не будет открываться).

После того, как были внесены все необходимые правки, сохраните файл. (Для того, чтобы изменения вступили в силу, может потребоваться перезагрузка компьютера).
Windows 7
Для изменения hosts в Windows 7 вам также требуется запустить блокнот от имени администратора, для этого вы можете найти его в меню «Пуск» и нажать правой кнопкой мыши, после чего выбрать запуск от имени администратора.

После этого, также, как и в предыдущих примерах, вы можете открыть файл и вносить необходимые изменения в нем.
Как изменить или исправить файл hosts с помощью сторонних бесплатных программ

Многие сторонние программы для исправления проблем работы сети, настройки Windows или удаления вредоносных программ содержат также и возможности изменения или исправления файла hosts. Приведу два примера.В бесплатной программе DISM++ для настройки функций Windows 10 со многими дополнительными функциями в разделе «Дополнительно» присутствует пункт «Редактор hosts».
Всё, что он делает — запускает всё тот же блокнот, но уже с правами администратора и открытым нужным файлом. Пользователю остается лишь внести изменения и сохранить файл. Подробнее о программе и где её скачать в статье Настройка и оптимизация Windows 10 в Dism++.
Учитывая то, что нежелательные изменения файла hosts обычно появляются в результате работы вредоносных программ, логично, что средства для их удаления могут содержать и функции исправления этого файла. Есть такая опция и в популярном бесплатном сканере AdwCleaner.

Достаточно зайти в настройки программы, включить пункт «Сбросить файл hosts», после чего на главной вкладке AdwCleaner выполнить сканирование и очистку. В процессе также будет исправлен и hosts. Подробно об этой и других таких программах в обзоре Лучшие средства удаления вредоносных программ.
Создание ярлыка для изменения hosts
Если вам часто приходится исправлять hosts, то вы можете создать ярлык, который будет автоматически запускать блокнот с открытым файлом в режиме администратора.

Для этого кликните правой кнопкой мышки в любом свободном месте рабочего стола, выберите «Создать» — «Ярлык» и в поле «Укажите расположение объекта» введите:
Затем нажмите «Далее» и укажите имя ярлыка. Теперь, кликните правой кнопкой мыши по созданному ярлыку, выберите «Свойства», на вкладке «Ярлык» нажмите кнопку «Дополнительно» и укажите, чтобы программа запускалась от имени администратора (иначе у нас не получится сохранить файл hosts).

Надеюсь, для кого-то из читателей инструкция окажется полезной. Если же что-то не получается, опишите проблему в комментариях, я постараюсь помочь. Также на сайте присутствует отдельный материал: Как исправить файл hosts.
A Guide to Hosts File and Using it to Block Websites on Windows, Linux, and Mac OS
![]()
Do you encounter a lot of ads and spam websites while browsing the internet? Do you want to block access to certain websites on your PC? The solution you’re looking for is called hosts file! In the below article, we will discuss the host's file and how to edit it in Windows, Linux, and Mac operating systems.
A hosts file in any system is a file maintained by the system’s OS that links a hostname to its respective IP address. The hosts file helps address various nodes in the network by translating a numeric IP address into a human-understandable name. It usually is present as operating system implementation and is stored as plaintext or ASCII document.
Why Would I Need to Edit My Hosts File?
Most basically, a hosts file can be used to override your DNS server, allowing a user to create a custom URL for any website of their liking. This custom URL can be mapped to the IP address of the website they want it to redirect to, making it possible to use alternate URLs for popular websites.
However, it is to be noted that the hosts file only applies to your local machine, meaning that the custom URL will only work on your system whose hosts file was edited.
There are a few benefits of maintaining or editing your hosts file manually.
- While not most important, to speed up the address resolution process of your web browser.
If you regularly visit a few websites, you can use the hosts file to speed up the loading time, although only by a few milliseconds. - The more important use of a hosts file would be to block ads and malicious websites.
These malicious websites could either contain malware, spyware or be simply annoying with their constant pop-ups. These websites can be blocked using the hosts file by merely mapping them to the loopback IP, i.e., 127.0.0.1. - Another primary use of the hosts file is to test a new domain that has been newly created or migrated from another server without altering the DNS server just yet. It is always advised not to make changes to the DNS until it confirms that the website is working perfectly.
So, a website test can be run locally by mapping the hosts file to the new server instead of altering the DNS immediately. Once the testing is finished and the website works properly, only then migrate the DNS information to the new server.
How to Edit Your Windows Hosts File
The hosts file is store as a txt file in the Windows operating system and can be found in the ‘System32’ folder in the C drive. In different versions of Windows, editing the hosts file is quite different. If using Windows XP or earlier versions, editing the hosts file was as easy as simply opening it in notepad, making changes, and saving it.
But in later versions, if you attempt to edit them similarly, you are bound to receive an error (see figure below) claiming that you don’t have appropriate permission to do so. An additional level of permissions was added to the process requiring administrator access to save changes to a hosts file in these versions.
This was mainly done to prevent other users on the PC from making changes to the hosts file for their own benefits or accessing websites restricted by the administrator.
Windows 10 & Windows 8
Editing the hosts file in these two Windows OS versions is quite similar. The following steps have to be followed if you want to edit the hosts file on your windows 10 or windows 8 PC:
- Open start menu
- Search for ‘Notepad’ in the search box
- When the notepad icon appears, right-click on it and select run as administrator
4. In notepad, go to File-Open or press Ctrl + O
5. In the ‘Open’ dialog box, navigate to C:\Windows\System32\Drivers\etc\hosts and open the hosts file. You might have to change the file type to ‘All Files’ instead of txt files in the dialog box.
6. Make all necessary changes to this file
7. New domain mapping can be added at the bottom of the file by specifying the IP address and custom domain name.
8. Save the file and close the notepad
Windows 7 & Windows Vista
The steps here are almost the same as before with small changes
- Open Start menu
- Navigate to Accessories-Notepad
- Right-click on ‘Notepad’ and select run as administrator
4. A dialog box pops up asking for admin permission; click yes here
5. In notepad, go to File-Open or press Ctrl + O
6. In the ‘Open’ dialog box, navigate to c:\Windows\System32\Drivers\etc\hosts
7. You might have to change the file type to ‘All Files’ instead of txt files in the dialog box
8. Open the hosts file and make all necessary changes
9. New domain mapping can be added at the bottom of the file by specifying the IP address and custom domain name
10. Save the file and close the notepad
How to Edit Your Hosts File in a Linux OS
If you are using a Linux-based operating system, the process to edit your hosts file will be entirely different, obviously. The hosts file will again be stored in plain text in a Linux OS and located at /etc/hosts. You would also require either root access or sudo user privilege in order to be able to edit the hosts file.
The following are the steps to edit the hosts file in a Linux system and can be applied for all Linux distros as long as you have access to a terminal.
- Launch a terminal on your Linux OS
- In the terminal window, open the hosts file with any available text editor (Vim, Nano, Emacs, etc.) using the sudo command
- The full path to the hosts file is /etc/hosts
- Enter the sudo password
- Scroll to the bottom of the text editor to add any new mappings to the hosts file or edit previous ones
6. The format for mapping can be copied from already existing lines
7. Save changes to the file and press Ctrl + X to exit
8. Press Y when prompted whether changes should be saved
How to Edit Your Hosts File in a Mac Operating System
Even though most people use Macs for non-programming-based use, it becomes quite a powerful PC once that side of a Mac opens up. Even though easy to use, Macs are highly efficient machines mostly due to their Unix root, much like a Linux OS.
This also means that a system running Mac OS has a terminal making the process of editing the hosts file quite similar to that in the Linux system.
- Launch a new terminal
- In the terminal window, use the path /etc/hosts to open the hosts file with any text editor of your choice
- The sudo command is to be used while opening the hosts file
- Enter the sudo password
5. As before, scroll to the bottom of the editor, add or remove lines for IP mapping.
6. Save changes and quit the text editor
7. You may sometimes have to flush your DNS cache for the changes to take effect or prevent clashes. To do this, type in the following command sudo dscacheutil -flushcache
How to Block Websites Using the Hosts File
The basic format of a hosts file mapping looks as below
The curly braces are only meant as a separator for each section and aren’t part of the syntax. Each section is usually separated by a space or tab.
The use of each section is as follows:
- The first section denotes the IP address to which the connection request will be directed to
- The second section is the hostname that initiates the redirect request
- The third and final section is for comments about the mapping
We can add a website on the hosts file that we require to be restricted/blocked on the specific system. In order to block a website using the hosts file, follow the steps listed below:
- First, based on your OS, open the hosts file as listed in the previous sections
- At the bottom of the hosts file, you can see a section of IP addresses with a domain name. This is where new websites can be added that need to be blocked. Refer to step five from the previous chapter above.
- Now, blocking of a website is usually done by mapping its domain name to the localhost IP address (127.0.0.1)
- In the hosts file, enter a new line with the localhost IP and the site’s domain name to be blocked. In our example, figure 11, we use the hosts file to block Facebook
5. The # is used to write a comment about the new mapping, which is only optional
6. Finally, once all websites to be blocked have been entered, save the file and exit
7. To ensure that the website has been blocked, simply open the command prompt and ping the website. In our case, the command is >ping facebook.com
8. From figure 12, it can be seen that the OS is trying to ping 127.0.0.1, which means Facebook has been blocked successfully with the hosts file.
Conclusion
The hosts file exists in a PC to resolve and map domain names to IP addresses. Although most users might not bother maintaining the hosts file, doing so has many benefits provided by the OS. In this article, we discussed some of these benefits and looked at editing a hosts file in the Windows, Linux, and Mac Operating systems.
If you enjoyed reading this article, or if you have any shortcut methods to maintain a hosts file, please leave a comment below and let us know!
Как прописать строку в файл hosts?
Нужно добавить новую строку в хосте, как это правильно сделать?
Файл hosts можно переписывать "по-горячему".
Находится он в каталоге C:\Windows\System32\drivers\etc — там он и лежит. Расширения у него нет, так что ни одна программа с ним не сопоставлена. Поэтому система спросит, чем же вы хотите его открыть. Выбирайте стандартный виндовозный "Блокнот". Ну или если пользуетесь вместо "Проводника" каким-нибудь толковым файл-менеджером, запросто сможете открыть файл через файл-менеджер. Лично я пользуюсь FAR, где видны все скрытые файлы и папки и редактирование прямо в нём, без вызова дополнительных программ, включается одной клавишей.
Файл hosts состоит из строк. Если строка начинается с символа #, она является комментарием и на действие файла не влияет.
Обычные, рабочие строки имеют вид:
Где IP-адрес — это IPv4 адрес сервера, на который идёт перенаправление, а доменное_имя — это адрес сайта, который вы хотите перенаправить (как таковой, без указания протокола http или https). Между — разделитель: пробел, символ табуляции.
Самое распространённое перенаправление — это указание на тот самый компьютер, на котором всё и происходит. Для него зарезервирован адрес 127.0.0.1, и первая строка в файле hosts обычно такая:
Что означает: запрос к адресу localhost будет перенаправлен на эту машину.
Так можно перенаправить запрос к любому сайту. Допустим, вам не нравится выскакивающая на файлообменниках рекламная страница super-dengi.com — вы добавляете в файл hosts — причём не важно, последней будет эта строка, первой или какой ещё — новую строку:
И теперь обращение к тому сайту пойдёт не в интернет и не покажет рекламу, казино или что там было. Вместо этого запрос пойдёт к вашему собственному компьютеру, тот не найдёт у себя ничего подобного и покажет пустую страницу. Что сэкономит вам трафик и нервы.
Или, к примеру, вам известен внешний IP-адрес вашего сервера, и вы хотите обращения к, допустим, вконтактику, перенаправить на свой сервер. Где лежит специальная картинка, символизирующая ай-ай-ай для сотрудников, лазающих по соцсетям в рабочее время. Пишете:
Вуаля! Все обращения к контактику пошли на ваш сервер с указанным IP.
После внесения всех исправлений просто сохраняете файл, и он работает уже с новыми параметрами.