- Файл hosts в Windows 7/10 – где находится и как редактировать?
- Зачем нужен файл hosts и где он находится
- Как изменить файл hosts: открытие, редактирование и сохранение
- Как восстановить удаленный или измененный файл hosts
- Где находится файл hosts и как его отредактировать
- zenorocha / etc-hosts-on-win.md
- This comment has been minimized.
- ashikcse20 commented Sep 9, 2018
- This comment has been minimized.
- metalgina commented Sep 27, 2018
- This comment has been minimized.
- Benjaminlooi commented Sep 29, 2018
- This comment has been minimized.
- marieclairembanga commented Oct 25, 2018
- This comment has been minimized.
- Evil-cluster commented Oct 27, 2018
- This comment has been minimized.
- JoelAzaria commented Oct 29, 2018
- This comment has been minimized.
- lopugit commented Nov 9, 2018
- This comment has been minimized.
- lopugit commented Nov 9, 2018
- This comment has been minimized.
- beanstalkim commented Nov 15, 2018
- This comment has been minimized.
- priteshjha4u commented Nov 26, 2018
- This comment has been minimized.
- JonBee commented Nov 27, 2018
- This comment has been minimized.
- ncolsens commented Dec 29, 2018 •
- This comment has been minimized.
- bala0406 commented Jan 19, 2019
- This comment has been minimized.
- BunnyImran commented Feb 12, 2019
- This comment has been minimized.
- x011 commented Feb 13, 2019 •
- This comment has been minimized.
- htoonlynnkyaw commented May 26, 2019
- This comment has been minimized.
- MoraleJ commented Jun 22, 2019
- This comment has been minimized.
- illfated commented Jun 24, 2019
- This comment has been minimized.
- elmoiv commented Aug 4, 2019
- This comment has been minimized.
- tmusabaika commented Aug 13, 2019 •
- This comment has been minimized.
- Wagner-Rob commented Sep 11, 2019 •
- This comment has been minimized.
- KingRider commented Dec 10, 2019
- This comment has been minimized.
- durhambell commented Dec 13, 2019
- But In Response to Your Issue
Файл hosts в Windows 7/10 – где находится и как редактировать?
Проблемы с интернет-соединением – одно из самых распространенных последствий заражения компьютера вирусом. При этом сайты либо не открываются, либо вместо одного сайта пользователь попадает на другой, причем такое поведение может наблюдаться даже после удаления вируса. Причина? Изменение вредоносной программой системных настроек и файлов, среди которых одним из наиболее важных является файл hosts.
Зачем нужен файл hosts и где он находится
Об этом файле вы, наверное, уже что-то слышали, используется он, кажется, для блокировки сайтов или что-то в этом роде. Да, такой функционал в нем действительно заложен, но изначально использовался он для иных, более важных целей. Кстати, известно ли вам, что файл hosts присутствует не только в Windows 7/10, но также и в Linux, Mac OS и Android? Эта универсальность вовсе не случайна, ведь появился файл hosts ещё на заре Интернета.
Собственно, никакого Интернета в полном смысле этого слова тогда еще не было, а если что и было, так это небольшие локальные сети. Как и сейчас, компьютеры в них сообщались посредством IP-адресов, понятных машинам, но не очень-то удобных для пользователей. Тогда айтишники решили реализовать обращение к компьютерам по именам, что и сделали, однако IP-адреса никуда не делись, хостам для сообщения по-прежнему нужны были цифровые, а не аналоговые адреса.
Решение было найдено очень скоро. На каждый компьютер в локальной сети был разослан специальный файл Hosts со списком имен хостов и соответствующими им IP-адресами. Когда один компьютер обращался к другому по имени, последнее сопоставлялось с его цифровым адресом, и таким образом устанавливалась связь. Поначалу всё было чудесно, но ресурсов становилось всё больше, список в файле Hosts увеличивался, и рассылать его на ПК стало всё более проблематично. Потребовалось новое решение, и оно также было найдено. Таблица соответствий была перенесена в тогда уже сформировавшийся Интернет, образовав систему доменных имён, а файл Hosts стал по большому счёту не нужен.
Удалять его из своих операционных систем разработчики, однако, не стали. Он и сейчас присутствует в большинстве ОС, по-прежнему устанавливая соответствие между IP-адресом и доменом сайта и, как и раньше, запрос к нему имеет больший приоритет перед обращением к DNS-серверам, только вот его содержимое ныне стало не в пример беднее, ограничившись двумя записями, да и то неактивными. В настоящее время hosts используется в основном для блокировки сайтов и баннерообменных сетей, автоматического перенаправления с одного ресурса на другой, а также ускорения доступа к сайтам.
В ранних версиях Windows файл хост располагался в папке %windir%, начиная с NT его постоянным местом значится расположение C:/Windows/System32/drivers/etc. В редких случаях файл HOSTS располагается в иной папке, путь к нему можно определить в редакторе реестра, развернув ветку HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/services/Tcpip/Parameters и посмотрев значение параметра DataBasePath.
Как изменить файл hosts: открытие, редактирование и сохранение
Итак, где лежит hosts мы знаем, теперь давайте посмотрим, что с ним можно сделать, и зачем вообще может понадобиться его изменение. По сути, файл хост это обычный текстовый документ, только без расширения. Открыть его можно любым текстовым редактором, тем же штатным Блокнотом.
Есть также специальные утилиты вроде HostsEditor, но их использование в большинстве случаев, пожалуй, излишне. Содержимое файла hosts представлено краткими сведениями о его предназначении и двумя примерами использования. Синтаксис записей очень прост. Сначала идет IP-адрес, а через несколько пробелов после него указывается имя хоста. Например, IP 38.25.63.10 будет соответствовать адрес x.acme.com, а IP 127.0.0.1 или ::1 (для IPv6) – адрес локального компьютера (localhost).
Обратите внимание, что перед всеми строками стоит знак #, это означает, что строка закомментирована, то есть она неактивна, а это равносильно тому, как если бы файл был пустым. Работать он начнёт только тогда, когда вы добавите новую запись. Приведем пример, как изменить файл hosts в Windows 7/10 и заблокировать с его помощью сайт, перенаправив обращение на локальный компьютер. Допустим, мы хотим ограничить доступ к социальной сети Вконтакте. Для этого в конце файла добавляем такую строчку:
127.0.0.1 vk.com
Сохраняем файл HOSTS как любой другой текстовый файл, перезапускаем браузер и пробуем зайти на сайт. В результате вы получите ошибку «Не удается получить доступ к сайту». Работает это очень просто. Когда пользователь переходит на vk.com, браузер первым делом обращается к HOSTS и ищет в нём соответствие имени хоста и его IP-адреса, и, найдя, переходит по указанному IP-адресу, игнорируя службы DNS-серверов, так как обращение к файлу хост является приоритетным.
Само собой, на локальном компьютере никакой социальной сети нет, поэтому браузер возвращает ошибку. Таким образом можно блокировать любые ресурсы, прописывая их в HOSTS в столбик. Другой пример использования хост-файла – перенаправление на другой сайт в интернете. Тут всё то же самое, только вместо локального IP-адреса 127.0.0.1 прописывается адрес другого сайта. Кстати, этим часто грешат вирусы, изменяя HOSTS и добавляя в него редиректы на фишинговые ресурсы.
Вот почему так важно знать, как должен выглядеть файл hosts по умолчанию. Если вы его не редактировали, а в нём присутствуют незакомментированные записи, это должно стать поводом для беспокойства. Впрочем, изменять hosts могут также антишпионские утилиты, прописывая в него адреса блокируемых неблагонадёжных ресурсов. Изменения также способны вносить кейгены, используемые для обходной активации лицензионного программного обеспечения.
Как восстановить удаленный или измененный файл hosts
Выше мы рассмотрели основные принципы работы файла, а заодно узнали, как его отредактировать. Увы, не всё бывает так гладко. Нередко от пользователей поступают жалобы, что файл хост не удается открыть, а если удаётся, то не получается его отредактировать либо система автоматически удаляет из него добавленные строки. Основная тому причина заключается в отсутствии у пользователя соответствующих прав.
Редактирование должно осуществляться с повышенными привилегиями. Как открыть файл hosts от имени администратора, если в контекстном меню нет соответствующей опции? Очень просто. Зайдите в расположение исполняемого файла Блокнота или иного текстового редактора, кликните по нему ПКМ, в меню выберите «Запуск от имени администратора».
В интерфейсе редактора через меню Файл – Открыть найдите и откройте файл hosts, не забыв только в стандартном окне обзора выбрать «Все файлы» вместо «Текстовые документы».
В Windows 8.1 и 10 изменённый файл хост может очищаться средствами безопасности системы, в частности, встроенным Защитником Windows. Чтобы этого не происходило, hosts необходимо внести в список исключений. Запустите Защитник, перейдите на вкладку «Параметры» и слева выберите «Исключенные файлы и расположения».
Укажите путь к файлу hosts и сохраните настройки.
Больше система его проверять не будет, следовательно, внесённые вами изменения не будут отменены.
В Windows 10 исключения вносятся из компонента Центр безопасности Защитника Windows, вызванного из системного трея.
Нельзя также исключать проблемы при попытке сохранить отредактированный файл. Причина та же – недостаток прав. Решить эту проблему нетрудно. Так как система не позволяет сохранять отредактированный файл непосредственно в папку etc, сохраните его на рабочий стол (расширение, если будет присвоено, уберите).
Переименуйте исходный файл в hosts.old, а затем скопируйте в папку etc новый изменённый файл hosts с рабочего стола.
Есть и более радикальный способ, например, hosts можно отредактировать напрямую, загрузившись с любого LiveCD со встроенным файловым менеджером.
И последнее. Что делать, если файл hosts оказался изменён или удалён? Можно ли его как-то восстановить? На работу системы удаление этого файла никак не повлияет, если только вы не изменяли его с какими-то определёнными для себя целями. Что касается восстановления, то здесь есть несколько путей решения. Исходный файл hosts хоть и содержит данные, по сути, равносилен пустому файлу. Создайте на рабочем столе пустой текстовый файл, удалите его расширение и переместите его в папку etc, это и будет ваш новый hosts.
Где находится файл hosts и как его отредактировать
Изменить файл hosts в windows не так уж и сложно, причин его изменения может быть несколько, например вы хотите добавить туда IP адреса какого либо из своих новых сайтов что бы он открывался до того как обновятся DNS, или наоборот запретить определенным сайтам открываться.
Файл 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 вам нужно сделать следующее:
Перейти по адресу: C:\Windows\System32\drivers\etc после чего в папке ETC вы увидите искомый файл HOSTS.
Для того что бы изменить (отредактировать) файл hosts нужно кликнуть по нему правой кнопкой мыши и выбрать Открыть после чего вы убидите это меню:
В списке программ вам нужно выбрать Блокнот и нажать Ок, после чего файл hosts откроется как обычный текстовый документ, чем он по сути и является. После внесения правок вам останется его стандартно сохранить, как будто вы отредактировали документ .txt.
На это все, теперь вы знаете как быстро отредактировать файл hosts.
Подписывайте на канал , задавайте по данной теме любые вопросы и я вам обязательно помогу. Так же можете внести предложение по теме ‘Создание и настройка сайтов, уроки по Windows’ и следующая статья будет об этом.
zenorocha / etc-hosts-on-win.md
1. Get your IP Address
2. Modify your hosts file
For Windows 10 and 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.
- Click File > Save to save your changes.
For Windows 7 and Vista
- Click Start > All Programs > Accessories.
- Right-click Notepad and select Run as administrator.
- Click Continue on the Windows needs your permission UAC window.
- When Notepad opens, click File > Open.
- In the File name field, type C:\Windows\System32\Drivers\etc\hosts.
- Click Open.
- Make the necessary changes to the file.
- Click File > Save to save your changes.
For Windows NT, Windows 2000, and Windows XP
- Click Start > All Programs > Accessories > Notepad.
- Click File > Open.
- In the File name field, type C:\Windows\System32\Drivers\etc\hosts.
- Click Open.
- Make the necessary changes to the file.
- Click File > Save to save your changes.
This comment has been minimized.
Copy link Quote reply
ashikcse20 commented Sep 9, 2018
This comment has been minimized.
Copy link Quote reply
metalgina commented Sep 27, 2018
wow, well, you guys seem to be having all this fun editing your ‘hosts’ file, the problem is, and I’m running windows 7 because windows 10 is absolute GARBAGE, I, for the life of me, can’t SAVE the file!! I’ve tried it in DOS, I’ve tried using cmd, I’ve tried powershell, I’ve tried just using notepad, I’ve tried attribing it to different attribs to make it so I can write to the file, I’ve even tried editting the autoexec.bat to edit the file to add the correct address for my WMP and NOTHING!! I am so frustrated! I’ve been working on this thing for three hours I’m ready to light my computer on fire and run down the street naked. HELP.
This comment has been minimized.
Copy link Quote reply
Benjaminlooi commented Sep 29, 2018
@metalgina try cmd, powershell, notepad with Administrative privaledges?
This comment has been minimized.
Copy link Quote reply
marieclairembanga commented Oct 25, 2018
I can’t see the repo etc in notepad. Additionally when i navigate on my explorer I see the file hosts but it’s encoding when I open it
This comment has been minimized.
Copy link Quote reply
Evil-cluster commented Oct 27, 2018
To edit the hosts file in Windows 10 you need to do it from another OS, no matter if it is a live USB or just another OS in your computer, this is due to the fact that the system automatically opens this file just when you start your machine, and therefore it cannot be modified at the same time. To override this, you only need to do what I just mentioned, so that the hosts file doesn’t get open and you can easily modify it. The same happens with the rest of the system files.
I hope I’m helpful.
This comment has been minimized.
Copy link Quote reply
JoelAzaria commented Oct 29, 2018
To edit the hosts file in Windows 10 you need to do it from another OS, no matter if it is a live USB or just another OS in your computer, this is due to the fact that the system automatically opens this file just when you start your machine, and therefore it cannot be modified at the same time. To override this, you only need to do what I just mentioned, so that the hosts file doesn’t get open and you can easily modify it. The same happens with the rest of the system files.
I hope I’m helpful.
I’m on windows 10 and have customers on Win10. I see zero evidence that any of this has any basis in reality.
I edit my hosts file just fine from an admin cmd prompt.
This comment has been minimized.
Copy link Quote reply
lopugit commented Nov 9, 2018
To edit the hosts file in Windows 10 you need to do it from another OS, no matter if it is a live USB or just another OS in your computer, this is due to the fact that the system automatically opens this file just when you start your machine, and therefore it cannot be modified at the same time. To override this, you only need to do what I just mentioned, so that the hosts file doesn’t get open and you can easily modify it. The same happens with the rest of the system files.
I hope I’m helpful.
bro you are cooked
This comment has been minimized.
Copy link Quote reply
lopugit commented Nov 9, 2018
To edit the hosts file in Windows 10 you need to do it from another OS, no matter if it is a live USB or just another OS in your computer, this is due to the fact that the system automatically opens this file just when you start your machine, and therefore it cannot be modified at the same time. To override this, you only need to do what I just mentioned, so that the hosts file doesn’t get open and you can easily modify it. The same happens with the rest of the system files.
I hope I’m helpful.
I’m on windows 10 and have customers on Win10. I see zero evidence that any of this has any basis in reality.
I edit my hosts file just fine from an admin cmd prompt.
@frankarma is cooked
This comment has been minimized.
Copy link Quote reply
beanstalkim commented Nov 15, 2018
wow, well, you guys seem to be having all this fun editing your ‘hosts’ file, the problem is, and I’m running windows 7 because windows 10 is absolute GARBAGE, I, for the life of me, can’t SAVE the file!! I’ve tried it in DOS, I’ve tried using cmd, I’ve tried powershell, I’ve tried just using notepad, I’ve tried attribing it to different attribs to make it so I can write to the file, I’ve even tried editting the autoexec.bat to edit the file to add the correct address for my WMP and NOTHING!! I am so frustrated! I’ve been working on this thing for three hours I’m ready to light my computer on fire and run down the street naked. HELP.
I had the same problem. The workaround is pretty simple, copy the file to your desktop, edit it, then move it back.
Don’t ask me why. 🙂
This comment has been minimized.
Copy link Quote reply
priteshjha4u commented Nov 26, 2018
Alright, Do i need to restart my system after making the changes? It doesn’t seem to be working instantly.
This comment has been minimized.
Copy link Quote reply
JonBee commented Nov 27, 2018
@beanstalkim @metalgina The hosts file is owned by SYSTEM. In order to edit it with notepad, you’ll need to run notepad as an administrator.
@priteshjha4u Running «ipconfig /flushdns» in command prompt should force Windows to reload the hosts file, if I remember correctly.
This comment has been minimized.
Copy link Quote reply
ncolsens commented Dec 29, 2018 •
The hosts file works with all versions of windows, in most operating systems use a hosts file including your android phone. When editing the hosts file simply make the changes and then save the file, but since windows will not allow you to save it where it resides, save it to your desktop and then manually copy it to C:\windows\system32\drivers\etc. You will be prompted to overwrite the file select yes. Remember when you finish editing the hosts file to strip off the extension «.txt» for it to work. There is no need to reboot your system, just close and re-open your browser of choice. When editing the host file on android phones you will need to reboot the phone. for the changes to take effect
Additionally do not use your WAN IP in the hosts file. you should use either
0.0.0.0
or
127.0.0.1
Your IP address can change too often
This comment has been minimized.
Copy link Quote reply
bala0406 commented Jan 19, 2019
This comment has been minimized.
Copy link Quote reply
BunnyImran commented Feb 12, 2019
@beanstalkim
Thanks your solution worked!
This comment has been minimized.
Copy link Quote reply
x011 commented Feb 13, 2019 •
Don’t forget to issue :
To flush cached ip’s
This comment has been minimized.
Copy link Quote reply
htoonlynnkyaw commented May 26, 2019
This comment has been minimized.
Copy link Quote reply
MoraleJ commented Jun 22, 2019
Team, I don’t know if my question is valid here or not but trying hard with Google i came here on this link. and i think i will get help here.
**I want to use API service. And to get the service i need to generate Access Token. To generate Access Token I need to provide
I am trying to use » http:/127.0.01/ as Redirect URL as i want it on local server
But its not working. **
Can someone help me ? If this is irrelevant Question here then i can delete it..
This comment has been minimized.
Copy link Quote reply
illfated commented Jun 24, 2019
@MoraleJ : If you want to publish anything from your own computer (1270.0.1), you need to install configure and run some form of HTTP server, like Apache or Microsoft Internet Information Server service.
This comment has been minimized.
Copy link Quote reply
elmoiv commented Aug 4, 2019
I can’t see the repo etc in notepad. Additionally when i navigate on my explorer I see the file hosts but it’s encoding when I open it
This comment has been minimized.
Copy link Quote reply
tmusabaika commented Aug 13, 2019 •
Another way to edit the hosts file directly is to use I/O redirection from cmd. It will not restrict you from editing the hosts file like the gui.
Launch cmd with elevated privileges (as administrator)
cd / navigate to the etc folder then issue your host entries using the following syntax
echo host_entry >> target_file
e.g. echo 127.0.0.1 localhost >> hosts
This will append your host entries at the end of the hosts file. Make sure you use the double greater than sign >> because using a single one > results in ovewriting whatever is already in the hosts file.
This comment has been minimized.
Copy link Quote reply
Wagner-Rob commented Sep 11, 2019 •
I had trouble saving mine too, but it was actually a very simple reason. Right-click on the hosts file, opened properties, unchecked the «read-only» box, then saved it without issue. Now it resolves through DNS.
This comment has been minimized.
Copy link Quote reply
KingRider commented Dec 10, 2019
Team, I don’t know if my question is valid here or not but trying hard with Google i came here on this link. and i think i will get help here.
**I want to use API service. And to get the service i need to generate Access Token. To generate Access Token I need to provide
I am trying to use » http:/127.0.01/ as Redirect URL as i want it on local server
But its not working. **
Can someone help me ? If this is irrelevant Question here then i can delete it..
This comment has been minimized.
Copy link Quote reply
durhambell commented Dec 13, 2019
Team, I don’t know if my question is valid here or not but trying hard with Google i came here on this link. and i think i will get help here.
I want to use API service. And to get the service i need to generate Access Token. To generate Access Token I need to provide
Redirect URL..
I am trying to use » http:/127.0.01/ as Redirect URL as i want it on local server
But its not working.
Can someone help me ? If this is irrelevant Question here then i can delete it..
It doesn’t seem like any of the comments here are relevant anyway, 90% of them are actually about Windows filesystem (although the people talking about it probably don’t know they are talking about it). Ironically the reason some people are having trouble editing their hosts files is because it can be a really bad idea to edit the hosts file if you don’t know what you are doing, so Windows makes it very difficult to do on purpose.
(aside: Hosts File Editor is a pretty nice little utility to do this, and it has some neat features like pinging endpoints for verification, «hot swapping» hosts files, and enabling/disabling them from the system tray)
But In Response to Your Issue
It sounds like you are trying to register for some service that wants you to provide a URL in order to get an access token. I think Twilio does things like this, as do some email marketing services. If I understand correctly, you will not be able to do this using your local machine as a redirect, because the service will want a publicly facing URL, probably for verification. The IP address 127.0.0.1 is a loopback address (as is any IP address beginning with 127.), so it is only accessible from the machine itself by design.