How to edit hosts
How to edit hosts
How to Edit Your Hosts File on Windows, Mac, or Linux
Occasionally you may need to edit the hosts file on your machine. Your host file might have been edited maliciously in an attack, or as a prank. Alternatively, you may just want to control access to certain websites or control network traffic.
Computers have had hosts files since the ARPANET days. The hosts files were used to resolve host names for decades before the DNS system was implemented. Since they were used to aide in network name resolution, hosts files grew to become massive documents.
Microsoft, Apple, and other operating system developers have kept the hosts file around, which is why it varies very little between Windows, macOS, and Linux. The syntax stays mostly the same across all platforms. Most hosts files will have several entries for loopback. We can use that for the basic example for the typical syntax.
The first part will be the location to redirect the address to, the second part will be the address that you will want to redirect, and the third part is the comment. They can be separated by a space, but for ease of reading are typically separated by one or two tabs, or the equivalent amount of spaces.
Now let’s look at accessing the hosts files in different operating systems.
Editing the Hosts File on Windows 10 or 11
The hosts file is still present in the latest and greatest from Microsoft — Windows 10 and Windows 11 — despite being ancient by computer standards. It isn’t used much in in modern Windows networking, however.
The hosts file, like other files that can be found in the Windows folder, is protected. You need administrative privileges to move, edit, or delete the file.
You can use any plain text editor you want to modify the hosts file, however Notepad is perfectly adequate for the task. You don’t need to go download another one just for this job.
Hit the Start button, type “notepad” into the search, and then right-click it and hit “Run as Administrator.”
Click on “File” in the top left corner, hit “Open,” and then navigate to:
Make sure to change the select to “All Files (*.*)” rather than “Text Documents (*.txt).” The hosts file doesn’t have a file extension, so it won’t show up if you’re only displaying text documents. After you change that setting, locate the “hosts” fileand click open.
You can then edit the hosts file however you’d like. There are a few obvious things to do with it, like block or reroute internet traffic.
Editing the Hosts File on Windows 8 or 8.1
Editing the hosts file on Windows 8 and 8.1 is basically the same as Windows 10 or 11.
Just search for Notepad, right-click on Notepad in the search results list, and then choose “Run as Administrator.
Once you’ve opened Notepad, click “File” in the top right, click “Open,” and then navigate to the /etc/ folder:
You’ll be able to edit the hosts file like you would any other file. You can use it to block access to websites, if you want.
Tip: If you get an error notifying you that you don’t have permission, you didn’t actually run Notepad as administrator.
Windows 7
Accessing the hosts file in Windows 7 is the same as on newer versions of Windows. You need to run Notepad as administrator, navigate to the hosts file, and then open it up.
There are a few ways you can do this. The first is to find Notepad, right-click it, hit “Run as Administrator,” and then navigate to the hosts file. It is located at:
Alternatively, you can hit Windows+R to open up a Run window, and then enter the following command:
The command will run Notepad as administrator and automatically open the specified file.
Once notepad is open you can edit the file. In this example we will block Facebook. To do this just enter in the following after the # mark.
Note: You can also use the loopback address instead of 0.0.0.0, but that is basically up to personal preference.
Now that you have edited your Hosts file make sure to save it.
Now notice if we try to access Facebook in IE we can’t get to the page.
We also were not able to get to it in Google Chrome… (check notes at the end). Also for more info on editing your Hosts file, check out The Geek’s article on how to create a shortcut to quickly edit your Hosts file.
Edit The Hosts File On Ubuntu
In Ubuntu (and most Linux distributions) you can edit the hosts file directly in the Terminal. You can use your favorite command-line editor or your favorite GUI text editor. For this example we will use Vim, since it is one of the traditional text editors in Linux. Like Windows, Ubuntu’s hosts file is located in the /etc/ folder, though here it is in the root of the drive. The hosts file is protected, and your regular user account will not be able to edit it.
You’ll need to launch Vim prefaced by sudo, which is conceptually and functionally similar to “Run as Administrator” on Windows operating systems. Open up a Terminal, then enter:
You’ll need to enter your password before the command will execute.
Note: If you get a message notifying you that Vim is not installed, just run “sudo apt install vim” in a Terminal.
Now that it is open we can edit it to redirect Facebook into nothing. You will notice that with Ubuntu there is also a section for IPv6.
You can ignore the IPv6 section in most cases; just editing the IPv4 section should do what you need.
Now we can save the file and try to go to Facebook.com. When you set the address in the hosts file to 0.0.0.0, your computer can’t reach Facebook, and throws an error: “Unable to Connect.”
Note: If your browser has been configured to use DNS Over HTTPS and its own DNS Server, editing the hosts file will probably not block access.
Change the Hosts File on Any macOS Version
In macOS, accessing the hosts file is very similar to Ubuntu. Begin in terminal and use your favorite editor — it could even be a GUI-based text editor if you wish, but it is easier to use a command-line editor from the Terminal.
The file will look a lot like the hosts file found in Windows and Linux. Again we are going to redirect Facebook to 0.0.0.0.
Safari, just like a browser on Windows and Ubuntu, will be unable to connect to Facebook.
Why Isn’t The Hosts File Blocking Connections?
All of the major modern browsers offer DNS Over HTTPS (DOH). DOH encrypts your DNS requests so that they can’t be intercepted and read by third parties that might be snooping — in general, this is a great thing.
For our purposes here, it limits the utility of the hosts file. The hosts file can only be used to block internet traffic if your browser is deferring to the DNS Server specified in the Windows operating system. A lot of browsers will enable DNS Over HTTPS automatically and use their own DNS servers. That results in the browser completely bypassing the hosts file. It is possible to force your browser to use the DNS Server Windows specifies, but you’ll have to dig through your browser’s settings.
This should get you started in understanding the Hosts file and how it can help protect your computer. Under the right circumstances, you can use it to block sites that you don’t want a PC to be able to access.
How to Edit Your Hosts File in Windows 10
What is a Hosts File?
The hosts file is a local plain text file that maps servers or hostnames to IP addresses. This file has been in use since the time of ARPANET. It was the original method to resolve hostnames to a specific IP address. The hosts file is usually the first process in the domain name resolution procedure. Here is an example of a hosts file entry.
We use the above code as an example since it almost always included in every hosts file. Another example would be similar to the following entry.
We would add the above entry to our hosts file to associate the hostname (or domain name)В liquidweb.comВ with the IP addressВ 67.225.187.61. To provide a working example, let’s move on to the next section.
Why is a Hosts File Useful?
Let’s say we have just completed a migration to a new server. In order to see how our domains will look and operate on our new server before we move our DNS settings, we cannot just type in one of our current domain names as it will resolve to the old server we are moving away from (since we never move our DNS A records from the old server until we are sure the new site is working as expected).
So, to see how our domain will look on the new server, (without having to change our DNS records) we can simply modify our local hosts file to point the domain to the new servers IP. If our domain is liquidweb.com and the old IP is 67.225.187.61 and our new IP will be 72.30.35.10, we can temporarily comment out the current liquidweb.com entry (using a ‘#‘ symbol) and add an alternate entry which points to the new servers IP.
If we added the above entry to our hosts file, every time we open liquidweb.com in our browser, we will now be redirected to the 72.30.35.10 IP.
Where is the Hosts File Located?
The location of the hosts file will differ by operating system. The typical locations are noted below.
What Does a Hosts File Contain?
A hosts file contains entries similar to the following information. Your entries may differ significantly.
How Do I Edit my Hosts File?
Our \etc\hosts file is only editable as a Windows administrator. В Here is a short video on how to edit a hosts file.
Here are the directions on how to modify your hosts file.
Step 1.
Click the Windows button and type Notepad in the search bar.
Step 2.
Right click on Notepad and then Run as Administrator.
Step 3.
You’ll be asked, “Do you want to allow this app to make changes to your device?”. Choose Yes.
Step 4.
In Notepad, choose File then Open.
Step 5.
Navigate to C:\Windows\System32\drivers\etc\hosts or click the address bar at the top and paste in the path and choose Enter.  If you don’t readily see the host file in the /etc directory then select All files from the File name: drop-down list, then click on the hosts file.
Step 6.
Add the appropriate IP and hostname at the end of your hosts’ file, select Save, and then close the file.
Step 7.
Finally, you will want to flush your DNS cache for your computer to recognize changes to the file. Click the Windows button and search command prompt.
Step 8.
Type the following command in the terminal and press Enter
Conclusion
Modifying a hosts file has many benefits which can significantly impact how you view your new domain or website. Using this method to view a site allows us to see how any new changes affect the layout and functionality of a domain.
Should you have any issues when modifying this file, our Support Teams are filled with experienced Linux technicians and talented system administrators who have an intimate knowledge of how to facilitate this modification. We are always available to answer any inquiries with issues related to this article, 24 hours a day, 7 days a week 365 days a year.
If you are a Fully Managed VPS server, Cloud Dedicated, VMWare Private Cloud, Private Parent server, Managed Cloud Servers, or a Dedicated server owner and you are uncomfortable with performing any of the steps outlined above, we can be reached via phone at 800.580.4985, or via a chat or support ticket to assist you with this process.
Related Articles:
About the Author: David Singer
I am a g33k, Linux blogger, developer, student, and former Tech Writer for Liquidweb.com. My passion for all things tech drives my hunt for all the coolz. I often need a vacation after I get back from vacation.
Join our mailing list to receive news, tips, strategies, and inspiration you need to grow your business
How to edit hosts
Last updated on: 2019-07-23
Authored by: Rackspace Support
Modifying your hosts file enables you to override the domain name system (DNS) for a domain on a specific machine. DNS management is useful when you want to test your site without the test link prior to going live with SSL, verify that an alias site works prior to DNS changes, and for other DNS-related reasons. For information about changing your DNS settings, see Changing DNS settings on Linux.
Modifying your hosts file causes your local machine to look directly at the Internet Protocol (IP) address that you specify. Rackspace offers managed hosting solutions to assist with the handling of these resources.
Modifying the hosts file involves adding two entries to it. Each entry contains the IP address to which you want the site to resolve and a version of the Internet address. For example, add the following two entries points, www.domain.com and domain.com, to Rackspace’s current refreshed PHP5 (PHP5-ITK) cluster:
This article provides instructions for locating and editing the hosts file on the following operating systems:
After you add the domain information and save the file, your system begins to resolve to the IP address that you specified. When testing is complete, remove these entries.
Windows
If you are using a Microsoft operating system like Windows 10, Windows 8, Windows 7, and Windows Vista you must run Microsoft Notepad as an administrator.
Windows 10 and Windows 8
Use the following instructions if you’re running Windows 10 or Windows 8:
Press the Windows key.
Type Notepad in the search field.
In the search results, right-click Notepad and select Run as administrator.
From Notepad, open the following file:
c:\Windows\System32\Drivers\etc\hosts
Make the necessary changes to the file.
Select File > Save to save your changes.
Windows 7 and Windows Vista
Use the following instructions if you’re running Windows 7 or Windows Vista:
Select Start > All Programs > Accessories.
Right-click Notepad and select Run as administrator.
The Windows needs your permission UAC window appears.
Click Continue to grant permission.
In Notepad, select File > Open.
In the File name field, enter the following path:
C:\Windows\System32\Drivers\etc\hosts
Select Open.
Make the necessary changes to the file.
Select File > Save to save your changes.
Windows NT, Windows 2000, and Windows XP
Use the following instructions if you’re running Windows NT, Windows 2000, or Windows XP:
Linux
Use the following instructions if you’re running Linux:
Open a Terminal window.
Enter the following command to open the hosts file in a text editor:
Enter your domain user password.
Make the necessary changes to the file.
Press Control-X.
When you are asked if you want to save your changes, enter y.
MacOS X versions 10.0 through 10.12
This section provides instructions for modifying your hosts file if you are running MacOS X 10.0 through 10.12.
MacOS X 10.0 through 10.1.5
Use the following instructions if you’re running MacOS X 10.0 through 10.1.5:
Open /Applications/Utilities/NetInfo Manager.
To enable editing of the Network Information database (NetInfo), click the padlock icon in the lower-left corner of the window.
Enter your domain user password and select OK.
In the second column of the browser view, select the node named machines.
From the Edit menu, select Duplicate.
A confirmation alert appears.
Click Duplicate.
A new entry named localhost copy appears and its properties are displayed below the browser view.
Double-click the value of the ip_address property and enter the IP address of the other computer.
Double-click the value of the name property and enter the host name that you want use for the other computer.
Click the serves property and select Delete from the Edit menu.
From the File menu, select Save.
A confirmation alert appears.
Click Update this copy.
Repeat steps 6 through 12 for each additional host entry that you want to add.
From the NetInfo Manager menu, select Quit.
You do not need to restart the computer.
MacOS X 10.6 through 10.12
Use the following instructions if you’re running MacOS X 10.6 through 10.12:
On your computer, select Applications > Utilities > Terminal to open a Terminal window.
Enter the following command in the Terminal window to open the hosts file:
When you are prompted, enter your domain user password.
Edit the hosts file.
The file contains comments (lines that begin with the # symbol) and some default host name mappings (for example, 127.0.0.1 – local host ). Add your new mappings after the default mappings.
To save the hosts file, press Control+X.
When you are asked if you want to save your changes, enter y.
To force your changes to take effect, flush the DNS cache by entering the following command:
Share this information:
©2020 Rackspace US, Inc.
Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License
How to Find and Edit a Windows Hosts File
While the internet is only about 30 years old, in many ways the hosts file is a relic of its (not so ancient) past.
In most cases you probably won’t need to update your hosts file on Windows. But knowing where it is and how it works can be helpful if:
In this article we’ll cover what a hosts file is, how to edit it on Windows, and we’ll go over some neat tricks you can do with it.
What’s a hosts file anyway?
Back in the early days of the internet, before it was widespread, computers used a hosts file to map long, hard to remember IP addresses with much shorter, easier to remember hostnames.
For example, here’s a line you’ll find in many hosts files on Windows, Linux, and macOs:
That way, instead of having to remember a long IP address, all you had to do was visit localhost.
Why hosts files fell out of favor
The hosts files system worked well for the early internet, but there were a few major problems.
As the internet grew, so did the length and complexity of the hosts files. Also, each hosts file only worked for the computer it was on, and keeping them in sync with the changes in hostnames and IP addresses became a huge pain.
For example, imagine that you have two computers, A and B. Their hosts files contain this mapping for google.com:
Computer A and B’s hosts file
But when Google updates their IP addresses, only computer A updates its hosts file to match:
Computer A’s updated hosts file
So everyone on computer B is stuck without Google until someone updates the hosts file. When that person does update the hosts file, they add another entry to handle Google with the www subdomain.
Computer B’s newly updated hosts file
Now everyone on computer B is taken to the correct website whether they visit google.com or www.google.com.
And everyone on computer A can only visit google.com, not www.google.com, at least until its own hosts file is updated to match.
As you can imagine, hosts files would get complicated, fast.
The solution
If you’re thinking that someone should have just made a central repository to map all IP addresses with all hostnames, that’s exactly what happened.
In the end, the humble hosts file and innovators like Elizabeth J. Feinler lead to the invention of the Domain Name System still in use today.
How to edit a hosts file on Windows
To edit a hosts file on Windows 10, you’ll need to open it as an administrator.
First, open Notepad as an administrator by pressing the Windows key, typing in «notepad», and clicking «Run as administrator»:
Note: You may need to click the arrow button to expand the dropdown to see the «Run as administrator» option
You won’t be able to see any files in this directory because they aren’t text documents. To change the file type, click on the dropdown in the bottom right of the Open menu and click on «All Files»:
Then, you’ll see a hosts file similar to this:
Windows 10’s default hosts file
With that out of the way, here are some things you can do with the hosts file.
How to update the hosts file on Windows 10 if you have trouble with localhost
If you’re doing some local development and are having problems with localhost, you can just remove the comments from your hosts file:
After saving the hosts file, close Notepad.
Then, open PowerShell by pressing the Windows key, searching for «powershell», and clicking «Run as Administrator»:
In the PowerShell window, enter ipconfig /flushdns to flush the inbuilt Windows DNS:
After that, you should be able to visit localhost in your browser and see whatever you’re hacking on. If you’re still having issues, try closing your browser completely, then open a new browser window and try again.
How to update your hosts file on Windows 10 if you think it’s been tampered with
Even though hosts files have fallen out of favor with newer systems like DNS, they still work for legacy reasons. And hackers have definitely taken advantage of this in the past.
What they would do is point a common website like google.com towards an unsafe IP address. This IP address could serve a site that looks just like Google’s, but is actually trying to steal your sensitive information.
While this was a problem in the past, most security software like the Windows Security Suite can recognize and fix problems with the hosts file automatically.
That said, if you open up your hosts file and see a lot of strange entries, then you may want to revert to the default Windows hosts file.
Just copy and paste the default hosts file from earlier in the article into your hosts file and save. Then, open PowerShell and use the ipconfig /flushdns command to flush the Windows DNS.
Note that some third-party security software uses the hosts file to block dangerous websites. If that’s the case, no worries – your security software should add all those entries back to your hosts file. We’ll go over how this works in the next section.
How to use the hosts file on Windows 10 to block websites
Don’t want friends or family to visit certain websites on your computer? Or are you like me and get distracted by all the cat photos on the internet?
If so, then you can use the hosts file to block websites entirely.
For example, if you want to block Reddit, just add this to the bottom of your hosts file:
Then, open PowerShell and run ipconfig /flushdns to flush the Windows 10 DNS. Also, close the browser windows that are open and reopen them.
Since there’s no website there, your browser will show an error message:
The one downside is that this only works on one device – you could just reach for your phone and browse Reddit on that instead. Still, it’s a neat way to create some friction on your work computer.
This leads nicely into the last trick, which is to use the hosts file to make your life a little bit easier.
How to use the hosts file on Windows 10 to set up helpful shortcuts
If you spend a lot of time adjusting your router’s settings, or you have a cool project running on a Raspberry Pi, you’ll know that typing in a long IP address is a drag.
Instead, you can use the hosts file to make connecting to other devices on your local network much faster.
Then, flush your Windows 10 DNS with ipconfig /flushdns and restart your browser.
To get around this, you could use a hostname like this instead:
Fortunately there are a whole lot of valid TLDs nowadays. Here’s a list of some of the most common TLDs out there: https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains
Again, the one downside to this method is that it only works on once device. You’d have to update the hosts files on your other devices to enable the same shortcuts.
And that should be just about everything you need to know about the hosts file on Windows 10. And a lot of this knowledge should carry over to Linux and macOS.
So get out there and customize your hosts file like the pioneers of the internet once did.
Did you find this helpful? Are there any other hosts file tricks you know? Let me know over on Twitter.
Файл hosts: где находится и как его изменить
Файл hosts — текстовый документ, который содержит в себе информацию о домене и IP-адресе, который ему соответствует. Файл 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
macOS — /private/etc/hosts
Редактировать файл etc hosts нужно от имени администратора, иначе вы не сможете сохранить внесённые изменения.
Как внести изменения в файл hosts
Ниже мы рассмотрим, как редактировать и как сохранить изменения в файле hosts. Важно открыть файл с правами администратора, иначе система не даст вам его сохранить. Выберите вашу операционную систему и следуйте инструкции или посмотрите видеоинструкцию:
Запустите Блокнот или любой другой редактор от имени администратора. Откройте Пуск, найдите нужный редактор, нажмите по нему правой кнопкой мыши и выберите Запуск от имени администратора:
Как отредактировать файл hosts
В меню «Файл» нажмите Открыть и перейдите в каталог, в котором расположен файл hosts. Измените тип файла на «Все файлы»:
Добавьте в конце файла необходимую запись в формате:
123.123.123.123 — IP-адрес вашего сервера или хостинга,
faq-reg.ru — имя вашего домена.
Теперь вы можете открыть ваш сайт в браузере, не дожидаясь обновления DNS-серверов.
Чтобы изменить файл hosts в виндовс 10 (8), выполните следующие действия:
Запустите Блокнот или любой другой редактор от имени администратора. Для этого найдите его в Пуске, нажмите по нему правой кнопкой мыши и выберите Запуск от имени администратора:
Добавьте в конце файла необходимую запись в формате:
123.123.123.123 — IP-адрес вашего сервера или хостинга,
faq-reg.ru — имя вашего домена.
Теперь вы можете открыть ваш сайт в браузере, не дожидаясь обновления DNS-серверов.
В Linux файл hosts находится в папке etc. Чтобы отредактировать его:
Введите в терминал linux команду hosts: sudo nano /etc/hosts
Добавьте в конце файла необходимую запись в формате:
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 — IP-адрес вашего сервера или хостинга,
faq-reg.ru — имя вашего домена.
Теперь вы можете открыть ваш сайт в браузере, не дожидаясь обновления DNS-серверов.
Видеосправка. Как изменить файл hosts
Также вы можете заблокировать определенный сайт через файл hosts, воспользовавшись инструкцией ниже:
Блокировка доступа к сайту через файл hosts
Доступ к сайту также можно ограничить для локального компьютера. Для этого укажите адрес страницы (домен) в файле hosts. Заблокировать IP нежелательного сайта не требуется. Блокировка осуществляется по локальному хосту с фиксированным IP (127.0.0.1):
В указанной на скриншоте строке укажите IP-адрес 127.0.0.1 и через пробел адрес нежелательного сайта. Чтобы заблокировать несколько сайтов, повторите действие в следующей строке. В примере ниже в файле hosts отказано в доступе (заблокирован доступ) к сайтам «vk.com» и «youtube.com»:
Готово! Доступ к сайтам будет ограничен на определенном ПК.
Оригинальный файл hosts и как его восстановить
Скачать содержимое файла hosts можно на разных ресурсах. Но мы не рекомендуем делать это, так как файл может быть заражен.
Файл hosts по умолчанию есть в каждой операционной системе, но он может быть скрыт для просмотра. Следуя инструкциям выше, вы сможете его открыть и отредактировать. Если вы удалили его, то просто создайте текстовый файл без расширения в нужной папке.
По умолчанию файл hosts выглядит следующим образом:
Источники информации:
- http://www.liquidweb.com/kb/edit-host-file-windows-10/
- http://docs.rackspace.com/support/how-to/modify-your-hosts-file/
- http://www.freecodecamp.org/news/how-to-find-and-edit-a-windows-hosts-file/
- http://help.reg.ru/hc/ru/articles/4408047489169-%D0%A4%D0%B0%D0%B9%D0%BB-hosts-%D0%B3%D0%B4%D0%B5-%D0%BD%D0%B0%D1%85%D0%BE%D0%B4%D0%B8%D1%82%D1%81%D1%8F-%D0%B8-%D0%BA%D0%B0%D0%BA-%D0%B5%D0%B3%D0%BE-%D0%B8%D0%B7%D0%BC%D0%B5%D0%BD%D0%B8%D1%82%D1%8C