修改window本地hosts文件,修改域名指向

时间:2021-10-25 13:49:32
Hosts是一个没有扩展名的系统文件,可以用记事本等工具打开,其作用就是将一些常用的网址域名与其对应的IP地址建立一个关联“数据库”,当用户在浏览器中输入一个需要登录的网址时,系统会首先自动从Hosts文件中寻找对应的IP地址,一旦找到,系统会立即打开对应网页,如果没有找到,则系统会再将网址提交DNS域名解析服务器进行IP地址的解析。
浏览器访问网站,要首先通过DNS服务器把要访问的网站域名解析成一个唯一的IP地址,之后,浏览器才能对此网站进行定位并且访问其数据。
操作系统规定,在进行DNS请求以前,先检查系自己的Hosts文件中是否有这个域名和IP的映射关系。如果有,则直接访问这个IP地址指定的网络位置,如果没有,再向已知的DNS服务器提出域名解析请求。也就是说Hosts的IP解析优先级比DNS要高。
以上内容均从百度百科复制。
文件路径:C:\WINDOWS\system32\drivers\etc。

如何修改hosts文件

hosts文件原内容如下:
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host # localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost

在最后新增如下内容:

127.0.0.1 www.163.com

表示域名“www.163.com”指向的ip为127.0.0.1,即本地。修改后文件内容如下:

# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host # localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
127.0.0.1 www.163.com

修改后用浏览器访问“www.163.com”会被解析到127.0.0.1,导致无法显示该网页。

修改window本地hosts文件,修改域名指向

为了进一步验证,使用tomcat在本地启动一个Web服务。tomcat版本为:apache-tomcat-8.5.4,其他版本应该操作类似。

下载解压tomcat后,运行apache-tomcat-8.5.4\bin\startup.bat,待tomcat启动成功,本地就有了一个Web服务了。

这时再访问"www.163.com:8080",就可以看到有页面内容了:

修改window本地hosts文件,修改域名指向

为什么要加上8080呢,因为这是端口号,tomcat开启的Web服务默认使用8080端口,而浏览器中默认的是80端口,所以必需要显示指明。也可以修改tomcat安装目录下的config/server.xml中的8080为80,这样就不用在访问时显式指定端口了。

这就是通过修改hosts文件来使域名指向某个IP的方式了,如果需要添加多条配置,直接再新增一行内容就行了。