Skip to content

修改 hosts 文件指南

hosts 文件是操作系统中的一个系统文件,用于将域名映射到 IP 地址。当你在浏览器中输入域名时,系统会优先查找 hosts 文件,如果找到对应条目,就直接使用该 IP 地址,不再通过 DNS 查询。

常见用途

  • 开发测试:将域名指向本地服务器
  • 网络调试:测试不同服务器环境
  • DNS 问题绕过:手动指定域名解析

macOS

方法一:终端命令行(推荐)

备份原始文件:

bash
sudo cp /etc/hosts /etc/hosts.backup

编辑 hosts 文件:

bash
sudo nano /etc/hosts

在文件末尾添加映射,格式为:

IP地址    域名

例如:

127.0.0.1    test.local
192.168.1.100    myserver.local

保存退出:Ctrl + X,然后按 Y,最后按回车。

刷新 DNS 缓存:

bash
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder

方法二:Finder 图形界面

  1. 打开 Finder,按 Cmd + Shift + G
  2. 输入 /etc/hosts,点击"前往"
  3. 将 hosts 文件复制到桌面
  4. 用文本编辑器打开并修改
  5. 将修改后的文件拖回 /etc/ 目录,输入管理员密码确认

Windows

hosts 文件位于:C:\Windows\System32\drivers\etc\hosts

方法一:记事本编辑(推荐)

  1. 在开始菜单搜索"记事本"
  2. 右键选择"以管理员身份运行"
  3. 点击"文件" → "打开"
  4. 导航到 C:\Windows\System32\drivers\etc\
  5. 文件类型选择"所有文件 (.)"
  6. 选择 hosts 文件并打开
  7. 在末尾添加映射,保存

刷新 DNS 缓存:

以管理员身份打开命令提示符:

cmd
ipconfig /flushdns

方法二:PowerShell

powershell
# 备份
Copy-Item C:\Windows\System32\drivers\etc\hosts C:\Windows\System32\drivers\etc\hosts.backup

# 编辑
notepad C:\Windows\System32\drivers\etc\hosts

编辑保存后刷新 DNS:

powershell
ipconfig /flushdns

验证修改

bash
# macOS / Linux
cat /etc/hosts
ping test.local

# Windows
type C:\Windows\System32\drivers\etc\hosts
ping test.local

常用配置示例

本地开发环境

127.0.0.1    localhost
127.0.0.1    dev.mysite.com
127.0.0.1    api.mysite.com

指向特定服务器

192.168.1.100    staging.mysite.com
10.0.0.50        internal.company.com

临时禁用条目

在行首添加 # 注释掉:

# 127.0.0.1    temp.local

恢复原始设置

bash
# macOS / Linux
sudo cp /etc/hosts.backup /etc/hosts

# Windows
copy C:\Windows\System32\drivers\etc\hosts.backup C:\Windows\System32\drivers\etc\hosts

注意事项

安全提醒

  • 修改前务必备份原始文件
  • 错误的配置可能导致网络访问异常
  • 定期检查 hosts 文件是否被恶意软件篡改
  • 修改完成后记得刷新 DNS 缓存