Hosts file path in windows

Файл 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 в Windows 7

  1. 1.

    Запустите Блокнот или любой другой редактор от имени администратора. Откройте Пуск, найдите нужный редактор, нажмите по нему правой кнопкой мыши и выберите Запуск от имени администратора:



    редактирование файла hosts в Windows 7
    Как отредактировать файл hosts

  2. 2.

    В меню «Файл» нажмите Открыть и перейдите в каталог, в котором расположен файл hosts. Измените тип файла на «Все файлы»:



    редактирование файла hosts в Windows 7

  3. 3.

    Выберите файл hosts и откройте его.

  4. 4.

    Добавьте в конце файла необходимую запись в формате:

    123.123.123.123 faq-reg.ru www.faq-reg.ru

    Где:

    • 123.123.123.123 — IP-адрес вашего сервера или хостинга,
    • faq-reg.ru — имя вашего домена.



    редактирование файла hosts в Windows 7

  5. 5.

    Сохраните изменения в файле.

Теперь вы можете открыть ваш сайт в браузере, не дожидаясь обновления DNS-серверов.


Редактирование файла hosts в Windows 8, 10

Чтобы изменить файл hosts в виндовс 10 (8), выполните следующие действия:

  1. 1.

    Запустите Блокнот или любой другой редактор от имени администратора. Для этого найдите его в Пуске, нажмите по нему правой кнопкой мыши и выберите Запуск от имени администратора:



    редактирование файла hosts в Windows 8, 10

  2. 2.

    В меню «Файл» нажмите Открыть и перейдите в каталог, где находится файл hosts. Измените тип файла на «Все файлы»:



    редактирование файла hosts в Windows 7

  3. 3.

    Выберите файл hosts и откройте его.

  4. 4.

    Добавьте в конце файла необходимую запись в формате:

    123.123.123.123 faq-reg.ru www.faq-reg.ru

    Где:

    • 123.123.123.123 — IP-адрес вашего сервера или хостинга,

    • faq-reg.ru — имя вашего домена.



    редактирование файла hosts в Windows 7

  5. 5.

    Сохраните изменения в файле.

Теперь вы можете открыть ваш сайт в браузере, не дожидаясь обновления DNS-серверов.


Редактирование файла hosts в Linux, Unix

В Linux файл hosts находится в папке etc. Чтобы отредактировать его:

  1. 1.

    Введите в терминал linux команду hosts:



    редактирование файла hosts в Linux, Unix

  2. 2.

    Добавьте в конце файла необходимую запись в формате:

    123.123.123.123 faq-reg.ru www.faq-reg.ru

    Где:

    • 123.123.123.123 — IP-адрес вашего сервера или хостинга,

    • faq-reg.ru — имя вашего домена.



    редактирование файла hosts в в Linux, Unix

  3. 3.

    Сохраните изменения в файле.

Теперь вы можете открыть ваш сайт в браузере, не дожидаясь обновления DNS-серверов.

Файл hosts в Ubuntu редактируется так же, как и во всех Unix-системах.


Редактирование файла hosts в MacOS

Файл hosts в Mac OS расположен в каталоге: /private/etc/hosts. Чтобы изменить его:

  1. 1.

    Запустите терминал с помощью горячих клавиш: Command (⌘) + T или через Spotlight.

  2. 2.

    Введите команду:

    Нажмите Enter:



    редактирование файла hosts в MacOS

  3. 3.

    Добавьте в конце файла необходимую запись в формате:

    123.123.123.123 faq-reg.ru www.faq-reg.ru

    Где:

    • 123.123.123.123 — IP-адрес вашего сервера или хостинга,

    • faq-reg.ru — имя вашего домена.



    редактирование файла hosts в Windows 7

  4. 4.

    Сохраните изменения в файле.

Теперь вы можете открыть ваш сайт в браузере, не дожидаясь обновления DNS-серверов.

Видеосправка. Как изменить файл hosts

Также вы можете заблокировать определенный сайт через файл hosts, воспользовавшись инструкцией ниже:

Блокировка доступа к сайту через файл hosts

Доступ к сайту также можно ограничить для локального компьютера. Для этого укажите адрес страницы (домен) в файле hosts. Заблокировать IP нежелательного сайта не требуется. Блокировка осуществляется по локальному хосту с фиксированным IP (127.0.0.1):

  1. 1.

    Откройте файл hosts от имени администратора на своём ПК.

  2. 2.

    В указанной на скриншоте строке укажите IP-адрес 127.0.0.1 и через пробел адрес нежелательного сайта. Чтобы заблокировать несколько сайтов, повторите действие в следующей строке. В примере ниже в файле hosts отказано в доступе (заблокирован доступ) к сайтам «vk.com» и «youtube.com»:



    блокировка доступа к сайту через файл hosts

  3. 3.

    Сохраните изменения.

Готово! Доступ к сайтам будет ограничен на определенном ПК.

Оригинальный файл 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

Для Linux

127.0.0.1       localhost

127.0.1.1      user

# 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

где user (во второй строке) — это имя вашего компьютера.

Для 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, вставьте текст по умолчанию и сохраните изменения.

Теперь вы знаете, как должен выглядеть файл hosts и как с ним работать.

Помогла ли вам статья?

Спасибо за оценку. Рады помочь 😊


 👍

From Wikipedia, the free encyclopedia

The computer file hosts is an operating system file that maps hostnames to IP addresses. It is a plain text file. Originally a file named HOSTS.TXT was manually maintained and made available via file sharing by Stanford Research Institute for the ARPANET membership, containing the hostnames and address of hosts as contributed for inclusion by member organizations. The Domain Name System, first described in 1983 and implemented in 1984,[1] automated the publication process and provided instantaneous and dynamic hostname resolution in the rapidly growing network. In modern operating systems, the hosts file remains an alternative name resolution mechanism, configurable often as part of facilities such as the Name Service Switch as either the primary method or as a fallback method.

Purpose[edit]

The hosts file is one of several system facilities that assists in addressing network nodes in a computer network. It is a common part of an operating system’s Internet Protocol (IP) implementation, and serves the function of translating human-friendly hostnames into numeric protocol addresses, called IP addresses, that identify and locate a host in an IP network.

In some operating systems, the contents of the hosts file is used preferentially to other name resolution methods, such as the Domain Name System (DNS), but many systems implement name service switches, e.g., nsswitch.conf for Linux and Unix, to provide customization. Unlike remote DNS resolvers, the hosts file is under the direct control of the local computer’s administrator.[2]

File content[edit]

The hosts file contains lines of text consisting of an IP address in the first text field followed by one or more host names.[3] The host names map to the IPs, not vice versa. Each field is separated by white space – tabs are often preferred for historical reasons, but spaces are also used. Comment lines may be included; they are indicated by an octothorpe (#) in the first position of such lines. Entirely blank lines in the file are ignored.[4] For example, a typical hosts file may contain the following:

127.0.0.1  localhost loopback
::1        localhost

This example only contains entries for the loopback addresses of the system and their host names, a typical default content of the hosts file. The example illustrates that an IP address may have multiple host names (localhost and loopback), and that a host name may be mapped to both IPv4 and IPv6 IP addresses, as shown on the first and second lines respectively.

Location in the file system[edit]

The location of the hosts file in the file system hierarchy varies by operating system. It is usually named hosts, without an extension.

Operating System Version(s) Location
Unix, Unix-like, POSIX /etc/hosts[5]
Microsoft Windows 3.1 %WinDir%\HOSTS
95, 98, ME %WinDir%\hosts[6]
NT, 2000, XP,[7] 2003, Vista,
2008, 7, 2012, 8, 10, 11
%SystemRoot%\System32\drivers\etc\hosts[8]
Windows Mobile, Windows Phone Registry key under HKEY_LOCAL_MACHINE\Comm\Tcpip\Hosts
Apple Macintosh 9 and earlier Preferences or System folder
Mac OS X 10.0–10.1.5[9] (Added through NetInfo or niload)
Mac OS X 10.2 and newer /etc/hosts (a symbolic link to /private/etc/hosts)[9]
Novell NetWare SYS:etc\hosts
OS/2, eComStation, ArcaOS «bootdrive»:\mptn\etc\
Symbian Symbian OS 6.1–9.0 C:\system\data\hosts
Symbian OS 9.1+ C:\private\10000882\hosts
MorphOS NetStack ENVARC:sys/net/hosts
AmigaOS < 4 AmiTCP:db/hosts
4 DEVS:Internet/hosts
AROS ENVARC:AROSTCP/db/hosts
Android /etc/hosts (a symbolic link to /system/etc/hosts)
iOS iOS 2.0 and newer /etc/hosts (a symbolic link to /private/etc/hosts)
TOPS-20 <SYSTEM>HOSTS.TXT
Plan 9 /lib/ndb/hosts
BeOS /boot/beos/etc/hosts[10]
Haiku /system/settings/network/hosts[11]
OpenVMS UCX UCX$HOST
TCPware TCPIP$HOST
RISC OS 3.7, 5 !Boot.Resources.!Internet.files.Hosts
later boot sequence !Boot.Choices.Hardware.Disabled.Internet.Files.Hosts[12]

History[edit]

The ARPANET, the predecessor of the Internet, had no distributed host name database. Each network node maintained its own map of the network nodes as needed and assigned them names that were memorable to the users of the system. There was no method for ensuring that all references to a given node in a network were using the same name, nor was there a way to read the hosts file of another computer to automatically obtain a copy.

The small size of the ARPANET kept the administrative overhead small to maintain an accurate hosts file. Network nodes typically had one address and could have many names. As local area TCP/IP computer networks gained popularity, however, the maintenance of hosts files became a larger burden on system administrators as networks and network nodes were being added to the system with increasing frequency.

Standardization efforts, such as the format specification of the file HOSTS.TXT in RFC 952, and distribution protocols, e.g., the hostname server described in RFC 953, helped with these problems, but the centralized and monolithic nature of hosts files eventually necessitated the creation of the distributed Domain Name System (DNS).

On some old systems a file named networks is present that is similar to a hosts file, containing names of networks.[13]

Extended applications[edit]

In its function of resolving host names, the hosts file may be used to define any hostname or domain name for use in the local system.

Redirecting local domains
Some web service and intranet developers and administrators define locally defined domains in a LAN for various purposes, such as accessing the company’s internal resources or to test local websites in development.[14]
Internet resource blocking
Entries in the hosts file may be used to block online advertising, or the domains of known malicious resources and servers that contain spyware, adware, and other malware. This may be achieved by adding entries for those sites to redirect requests to another address that does not exist or to a harmless destination such as the local machine.[15] Commercial software applications may be used to populate the hosts file with entries of known undesirable Internet resources automatically. In addition, user-created hosts files which block nuisance servers are publicly available.[16][17]
Fravia described these files variously as «scrolls», «precious», and «powerful» in his anti-advertisement pages, where this usage of hosts was first published.[17]
Software piracy
Some pirated versions of software rely on a modified hosts file to prevent software from contacting the activation servers of the publisher, although activation servers sometimes appear in general purpose hosts files.[18]

Security issues[edit]

The hosts file may present an attack vector for malicious software. The file may be modified, for example, by adware, computer viruses, or trojan horse software to redirect traffic from the intended destination to sites hosting malicious or unwanted content.[19] The widespread computer worm Mydoom.B blocked users from visiting sites about computer security and antivirus software and also affected access from the compromised computer to the Microsoft Windows Update website.

In some cases, malware has modified the library responsible for loading the hosts file in order to redirect it to a file it is able to control freely.[20]

See also[edit]

  • DNSBL, a DNS-based blackhole list
  • Content-control software
  • Ad filtering

References[edit]

  1. ^ Internet Systems Consortium. «The Most Widely Used Name Server Software: BIND». History of BIND. Retrieved 2017-07-01.
  2. ^ Cisco Networking Academy Program: First-Year Companion Guide (2nd ed.). Cisco Systems. 2002. p. 676. ISBN 1-58713-025-4.
  3. ^ Penetration Testing: A Survival Guide. Packt Publishing Ltd. 18 January 2017. ISBN 978-1-78728-988-8.
  4. ^ «Hosts(5) — Linux manual page».
  5. ^ «Linux Network Administrators Guide: Writing hosts and networks files». Retrieved May 16, 2010.
  6. ^ «Hosts File». Archived from the original on July 20, 2011. Retrieved August 10, 2011.
  7. ^ «Microsoft KB Q314053: TCP/IP and NBT configuration parameters for Windows XP». Retrieved August 28, 2010.
  8. ^ «Microsoft KB 972034 Revision 2.0: default hosts files». Retrieved August 28, 2010.
  9. ^ a b «Mac OS X: How to Add Hosts to Local Hosts File». Retrieved August 28, 2010.
  10. ^ «The Haiku/BeOS Tip Server». Archived from the original on January 28, 2013. Retrieved November 30, 2012.
  11. ^ «Haiku UserGuide:Network». Retrieved January 17, 2019.
  12. ^ RISC OS 6.14
  13. ^ «Writing hosts and networks Files». tldp.org. Retrieved 2021-03-02.
  14. ^ «Building / Testing via the Hosts File». Ohio State University Web Hosting. OCIO. 9 October 2015. Retrieved 5 August 2018.
  15. ^ Gordon; -Tx. «Gordon and -Tx explanations about the use of Gordon’s hosts file». Web Searchlores. +Fravia. Archived from the original on 26 December 2018. Retrieved 5 August 2018.
  16. ^ Hofstetter, Constantin. «/etc/hosts to block shock sites etc». GitHub. Retrieved 5 August 2018.
  17. ^ a b Vianello, Francesco «Fravia». «Antiadvertisement Lab». Web Searchlores. +Fravia. Retrieved 5 August 2018.
  18. ^ «yhosts». GitHub. Retrieved 21 June 2021.
  19. ^ «Remove Trojan.Qhosts». Symantec. Retrieved May 16, 2010.
  20. ^ Arntz, Pieter (21 September 2016). «Hosts file hijacks». Malwarebytes Labs. Retrieved 5 August 2018.

External links[edit]

  • Windows
    • Beginners Guide on Editing Hosts File
    • Microsoft TCP/IP Host Name Resolution Order
    • List of Microsoft domains that Windows won’t redirect with a host file
  • Mac
    • How to block unwanted domains with a HOSTS file on Mac OS X 10.2 or later
  • Linux
    • How to block unwanted advertisements with /etc/hosts file on Linux

The Hosts file in Windows 11/10, 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.

Lock, manage, edit Hosts File in Windows

The HOSTS file is 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. Moreover, the IP address and the host name should be separated by at least one space.

In this post, we will see its location and also how to manage, lock, or edit the Hosts file in Windows 11/10. We will discuss the following:

  • Host file location
  • Lock Hosts file to prevent hijacking
  • Block website using the Hosts file
  • How to edit the Hosts file
  • Using free Hosts File Editor software.

Let us take a look at them.

Host file location in Windows

The Hosts file in Windows is located at the following location:

C:\Windows\System32\drivers\etc

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:

127.0.0.1       blocksite.com

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 that block malware sites from opening.

How to edit Hosts file in Windows 11/10

To edit the Hosts file in Windows 11/10:

  1. Open Explorer
  2. Navigate to \System32\drivers\etc\ location
  3. Locate Hosts file
  4. Right-click on it and select Notepad
  5. Make the changes and Save.

Now let us go into a detailed explanation.

To edit the Hosts file, navigate to the following folder location:

C:\Windows\System32\drivers\etc\

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

Or

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.

Using free Hosts File Editor software

If you are looking for an easier way, you can use a free Hosts file Editor software.

1] Using 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.

Hosts file in Windows 8

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, it’s the only Hosts Manager that you will even need. You can download it from its home page.

2] Using SysMate Hosts File Manager

SysMate Hosts File Walker

SysMate Hosts File Manager and is another tool that lets you do so. With Host File Walker you can add as many records to the system hosts file. It even lets you backup and restore the Hosts File.

3] Using Host File Editor tool

Edit Hosts File in Windows 10

Host File Editor is another good tool that you can use. It has the following features:

  • Enable and disable hosts file from the system tray
  • Cut, copy, paste, duplicate, enable, disable and move entries
  • Filter and sort host entries
  • Backup and restore various hosts file configurations when switching between environments
  • Ping endpoints to check availability.

You can download it from here. It offers a portable version too.

4] HostsDock

HostsDock software

HostsDock is another useful software to edit the hosts file on Windows 11/10 computers. This is an open-source hosts file editor software that also lets you create new local hosts files and save them. You can also connect to a remote hosts file which is an important option. Some other interesting features are also available which are as follows:

  1. Syntax Highlighter that can automatically highlight IP addresses, comments, domains, etc., present in the hosts file. It detects all these items by itself and then highlights them
  2. Basic editing options like undo/redo, search and replace, cut, paste, etc.
  3. Create folding block
  4. Test IP addresses in the hosts file with the ping command
  5. A navigation pane to quickly switch to local and remote hosts files, check system hosts info, etc.

You can download this tool from eshengsky.github.io. Launch the tool after installation and it will show the system hosts file. After that, you can use the available options to add or create a new hosts file, use editing options, export the hosts file, and more.

5] Hosts File Editor PowerToy

Hosts File Editor PowerToy

The Hosts File Editor PowerToy also lets you edit the Hosts file.

How do I grant permission to edit the Hosts file in Windows 11/10?

If you want to grant permission to edit the hosts file in Windows 11/10 using Notepad, then you need to run Notepad as an administrator. You should also sign in to your Windows 11/10 system with an administrator account to edit hosts file so that you won’t get any errors while saving the hosts file.

Read: What is LMHOSTS file in Windows?

Do not have permission to edit the Hosts file?

If you are unable to edit the hosts file on Windows 11/10 or you do not have permission to edit the hosts file, then you can use the following solutions:

  1. Use Notepad with administrative privileges and then open a hosts file to edit it
  2. Copy the hosts file from the original location to the desktop or some other location, edit that file, and then copy the edited file and paste it into the original location to overwrite the hosts file
  3. Use some third-party hosts file editing tools, etc.

TIP: See this post if Hosts File is not working in Windows. How to manually reset the 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.

  • Find out what the hosts file does, where is the etc folder in Windows, and how you can edit its contents.
  • There are tons of old tools buried deep inside Windows.
  • The ETC Hosts file is one of these remnants, dating back to 1984.

Operating systems are complex “creatures”, even if on the outside they look friendly. OSes are among the most complex pieces of software out there. It’s a miracle they’re friendly enough to get things done by non-technical people.

Windows is no different, and even if we’re talking about the fresh new version of Windows 11, underneath not every bit is new. For legacy and compatibility reasons Microsoft can’t start from the beginning with Windows, no matter how hard we wish they did.

In this article, we’ll be talking about the etc/hosts file, which dates back to something like 1984, the year, not the book. Funny enough, the etc/hosts file can be used to control people’s behavior, but let’s not spoil things from the beginning.

What is the ETC/Hosts File?

The etc/hosts file is a text document stored inside the Windows folder. It acts as a local DNS server, where you can manually specify which domain names load from which IPs. The hosts file entries will override DNS settings coming from the Internet servers.

etc hosts file contents

CONTENTS

  • 1 What’s the Location of the Hosts File? Where Is The etc Folder in Windows?
  • 2 How to View the Contents of the Hosts File?
  • 3 How Can You Edit the Hosts File in Windows?
  • 4 How to Add Info to the Hosts file?
  • 5 What Can You Use the Hosts File For?

The hosts file is located in the etc directory in the Windows folder:

C:\Windows\System32\drivers\etc

Now you understand why it’s called etc/hosts, right?

etc hosts file location windows folder

How to View the Contents of the Hosts File?

Now, to view the hosts file contents do the following:

  1. Copy the path above.
  2. Open Windows Explorer (Win + E).
  3. Click on the address bar (or press Alt + D).
  4. Paste the path (Ctrl + V), then hit enter to open the hosts file location.

Since the hosts file is in text format you can use any text editor. And by any, I mean any program, even Notepad, which we’ll use for demo purposes.

  1. In the Windows Explorer window, right-click on the hosts file icon.
  2. Choose Open with.
  3. From the new popup click on Notepad and hit OK.

how to open file with notepad in windows

The file looks something like this. Below I’ve added the default version that comes with Windows 11. It’s surprisingly legible and has tons of useful info already laid out.

etc hosts file open in notepad

How Can You Edit the Hosts File in Windows?

Now, at this point, if you try and save the file, after modifying it (Ctrl + S), you’ll see the popup below, followed by a small error window that appears after you click Save.

etc hosts file cant save

That’s because you didn’t open Notepad with administrator privileges. The etc hosts file is a system file and can’t be modified by everyone. So, close the Notepad window, and let’s try again, but this time we’ll do things a bit differently.

1. Open the Start menu (press the Win key).

2. Type Notepad.

3. Right-click on the first result to open the contextual menu.

4. Click on Run as administrator.

start notepad as administrator

5. Select File > Open (or press Ctrl + O).

6. Navigate to the hosts file location.

7. If the folder appears empty it’s because in the open dialog window system files are hidden by default. Select All files (*.*) in the lower right dropdown menu.

open etc hosts file no extension

8. Select and open the hosts file.

9. Edit as you please then save with Ctrl + S.

That’s it, you’ve now modified the hosts file.

It would be a good idea to save a backup of the hosts file first, before editing. You can mess up quite a few things by mistake.

How to Add Info to the Hosts file?

The hosts file works like a table with two columns and an infinite number of rows.

You only need two bits of info on each row.

IP Host name
192.168.1.200 binaryfork.com

The line above will try and load my site from a different IP. It won’t work with this particular IP.

The IP and the host name must be separated by at least a space. You can use more spaces for formatting purposes.

Anything that starts with a # on a row is a comment and will be ignored. You can add a comment after a pair of IP-hostname on the same row to ensure you remember what that line does. You’ll definitely forget.

What Can You Use the Hosts File For?

I’m not going to lie to you: the first time I heard about the hosts file I only saw the prank possibilities opening up. If you can edit the hosts file on a friend’s computer you can for example point google.com to the IP of bing.com. Some friend, right?

Anyway, that’s not what the hosts file is used for. Developers need to test apps and websites locally, and the hosts file is a great way to point the browser to the domain name of the website you’re working on, but make sure it loads from your computer, not from the Internet.

So, IT professionals are the types of people who use this old Windows functionality.

As with any tool, even the etc/hosts file can be used for malicious purposes. Some malware and viruses are using this file to point your browser to copies of the websites you’re using, just to steal your information. Be careful and if anything looks weird when browsing the web it could be a good idea to double-check the hosts file contents by using the guide above.

Frequently Asked Questions About the Hosts File

What is the 127.0.0.1 IP address?

This number is known as localhost or loopback address and is the IP that when used will open the browser pointing to the local computer. Imagine you need to call yourself on the phone, to see if the speaker is working. On a normal phone, you can’t do that. With computers, you can.

Web developers are the kind of people who need to use the localhost functionality. Localhost works even on a PC not connected to the Internet.

Avatar for Ionuț-Alexandru Popa

I’m passionate about technology, science, and movies. I write about tech since 2003.

  1. What’s My DNS?

  2. Hosts File — How and why to edit your DNS Hosts File

The hosts file is a file on your computer or other device that is used as the first step in the DNS lookup process for DNS hostname resolution.

This is the process of converting a domain name like www.example.com into an IP address like 192.168.2.1 which computers and network devices use to communicate with each other.

Making changes to your systems hosts file lets you intercept the normal DNS lookup process and set any IP address for any domain name you like which can be useful for many reasons, but also potentially harmful in some circumstances.

The hosts file can be found in the following locations depending on your operating system:

  • Windows: C:\Windows\System32\Drivers\etc\hosts
  • Linux: /etc/hosts
  • MacOS: /etc/hosts

There are several reasons why you may be interested in viewing or editing your hosts file which include:

Testing DNS changes — A common use for making changes to the hosts file is to test changes to DNS records before making them live on the internet. This allows you to make sure a new server setup is behaving as expected before making the changes to your DNS setup and having them live for everyone.

Forcing DNS changes — Often when having made changes to your domain names DNS settings, you will need to wait for DNS propagation as you may have locally cached DNS records and are not seeing the expected updated results. You can flush your DNS cache, or modify your hosts file to temporarily force changes which are not updating fast enough.

Local development — Often setting up custom hostnames for local testing and development can be quite useful. This allows you to configure your system to respond to your local web server on https://www.mysite.test and have your real site live on https://www.mysite.com.

Ad & content blocking — As the hosts file lets you override DNS entries for any domain name, people often create hosts file entries for common tracking, spyware, malware domains as well as product activation servers to assist with software piracy. There are lists of common ad networks and tracking servers available online which you can use to keep an up-to-date list of sites to block. Blocking is achieved by setting the IP address of the ad networks to a loopback address like 127.0.0.1 which will not return anything.

Checking for compromise — Often if your device is infected with malware, then your hosts file may be compromised to included entries which could cause you harm. For example, if your hosts file had been unknowingly changed to point your banks domain name to the IP address of a hacker. This type of DNS attack is known as DNS pharming, and checking your hosts file can uncover potential infection.

Where is the hosts file located?

The most common question that many people have around the host file is how do you find it? What is the path and location of the hosts file?

Depending on your operating system, the hosts file is located in different locations and requires different methods for editing as it is a protected system file.

Windows host file location

The hosts file for all recent versions of Windows including Windows 7, 8, 10, 11 & Windows Server is located in C:\Windows\System32\Drivers\etc\hosts.

There are a few important notes to remember when opening the hosts file on Windows:

  • You will need to use a plain text editor like Notepad, not a word processor like Microsoft Word.
  • You will need to open the file as the local system administrator. This can be done by right clicking on for example Notepad and choosing «Run as administrator».
  • When navigating to the directory containing the hosts file, they may be hidden depending on your setup. Additionally you may need to select to show «All Files (*.*)» instead of the default «Text Documents (*.txt)».

Linux host file location

The hosts file for Unix, Linux and other Unix like operating systems is located in /etc/hosts

As this is a protected system file, you will need to make sure that you edit it as the root user. This can be done using sudo for example sudo vim /etc/hosts from the terminal.

Apple MacOS host file location

The hosts file for MacOS is located in /etc/hosts as MacOS is a Unix based system and follows many of the common file location conventions.

As this is a protected system file, you will need to make sure that you edit it as the root user. This can be done using sudo for example sudo vim /etc/hosts from the terminal.

How do you edit your hosts file?

Once you’ve found the location of your hosts file for your specific operating system, all you need to edit it is a simple plaintext text editor. You can use Windows Notepad, TextEdit on the Mac, as well as command line text editors like vim or nano on Unix based systems.

You will need to make sure that when you’re editing this file that you do so with an account which has administrator privileges as this is a protected system file.

Hosts file format

Once you have located the hosts file, the format is very simple. On a new blank line you need to enter the desired IP address followed by one or more spaces (or tabs) and then the hostname you would like to assign to this. You can add additional hostnames separated by one or more spaces (or tabs) as well.

IP address considerations:

You can use either IPv4 A Records or IPv6 AAAA Records for the IP address which you would like to assign.

If using an IPv6 address, you may want to consider using either the IPv6 expanded format or IPv6 compressed format for all IPv6 entries to ensure consistency and making searching for entries easier if you have large number of them.

Hostname considerations:

When specifying the host name for a hosts file entry, make sure to only include the domain name itself. Do not enter the protocol (http://), or document path (/some-page.html). For example for the webpage http://www.example.com/some-page.html the hostname would be simply www.example.com. If you would also like to include both example.com and www.example.com then you will need to specify both individually.

If using an International Domain Name (IDN), then it will first need to be converted to Punycode format as the host file is plain text and does not accept UTF-8 characters.

Wildcard domains (*.example.com) are not supported in the hosts file.

It is important to make sure that you use a plain text editor like Notepad rather than a word processor like Microsoft Word to edit the hosts file as advanced word processors can introduce unrecognized data like font information.

Example hosts file:

An example hosts file entry may look like the following:

127.0.0.1 example.com

or with multiple entries:

127.0.0.1 example.com
127.0.0.1 www.example.com

or multiple entries on a single line

127.0.0.1 example.com www.example.com

Hosts file comments:

It can sometimes be useful to add comments to your hosts file, especially if you have many entries or entries that you switch between from time to time.

To add a comment, you simply need to use the # character, and anything after this will be ignored.

# this entire line is a comment
127.0.0.1 example.com # this text at the end of a host file entry is a comment
# 127.0.0.2 example.com this entire line a comment and not a valid hosts file entry

The above only includes a single valid hosts file entry for example.com pointing to 127.0.0.1.

How to test changes made to the hosts file?

When you have made changes to your hosts file, you will not be able to use any of the Online DNS Tools to check your changes, instead you will need to rely on your local device for testing.

Using built in DNS tools like nslookup on Windows or dig on Linux and MacOS will query your devices locally configured nameservers directly, skipping reading the hosts file so is not an ideal way of testing changes.

One of the best methods is to use the ping command-line tool, simply run ping example.com and observe which IP address is resolved for the given hostname.

Which hosts file to edit when using Windows Subsystem for Linux (WSL)?

You may wonder which hosts file you need to edit when running multiple operating systems on Windows by taking advantage of WSL.

Making changes to the Linux guest operating systems hosts file at /etc/hosts file will only have changes reflected within the Linux instance.

Editing the Windows hosts file at C:\Windows\System32\Drivers\etc\hosts will have the changes reflected on both Windows and within the Linux instance.

  • How to activate windows with kms
  • Hostid как узнать windows 10
  • How to activate windows 11 for free
  • Host файл windows 10 скачать
  • How to activate windows 10 with cmd