C:\Windows\System32\drivers\etc\hosts (無副檔名)IP位址 主機名 [#註解],每行一筆,空白鍵/Tab 分隔。# 將常用網站 IP 寫入 Hosts,瀏覽器直接連線,跳過 DNS 查詢
142.250.190.46 www.google.com
142.250.190.46 drive.google.com
142.250.190.46 mail.google.com
104.18.32.68 github.com
104.18.33.68 assets-cdn.github.com
104.18.34.68 raw.githubusercontent.com
# 注意:IP 可能變更,建議定期 nslookup 更新,或改用智慧 DNS/DoH
優點:首次連線省去 DNS RTT (約 20-100ms)。
缺點:IP 變更會導致無法連線;CDN 多 IP、GeoDNS 導致非最佳節點;維護成本高。
現代替代:瀏覽器 DNS 預解析 (<link rel="dns-prefetch">)、系統級 DoH (DNS over HTTPS)、本地 DNS 快取 (systemd-resolved, dnsmasq, Unbound)。
# 開發/測試/內網環境
192.168.10.10 gitlab.company.local
192.168.10.11 jenkins.company.local
192.168.10.12 wiki.company.local
192.168.10.100 db-prod
192.168.10.101 redis-cache
# 團隊共享:將 hosts 檔納入版控 (Git) + 部署腳本自動分發/同步
適用於無內部 DNS 伺服器、或臨時測試、開發環境快速切換版本 (修改 Hosts 指向不同 IP)。
# 導向本機 (127.0.0.1) 或無效位址 (0.0.0.0)
0.0.0.0 ads.example.com
0.0.0.0 tracker.analytics.com
0.0.0.0 malware.badsite.com
127.0.0.1 porn.site.com
# 大型維護清單專案:StevenBlack/hosts (GitHub),定期更新,涵蓋廣告、追蹤、惡意、賭博、偽造等分類
機制:瀏覽器解析域名 → 取得 0.0.0.0/127.0.0.1 → 連線失敗/連回本機 → 資源載入失敗 → 頁面無廣告/追蹤碼。
優於瀏覽器擴充功能:系統級生效,覆蓋所有應用 (含 Electron 應用、命令列工具、系統更新)、無法被網頁腳本繞過。
# 已知正確 IP (從可信 DNS/海外查詢獲得)
104.18.32.68 github.com
140.82.114.4 github.com
# 強制解析至正確 IP,繞過本地 ISP DNS 劫持/污染
配合 ipconfig /flushdns 清除快取即時生效。
# 從 GitHub 更新 StevenBlack/hosts 並合併自定義項
$url = "https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts"
$custom = "C:\Custom\hosts.custom" # 自定義項
$target = "C:\Windows\System32\drivers\etc\hosts"
$content = (Invoke-WebRequest -Uri $url -UseBasicParsing).Content
if (Test-Path $custom) { $content += "`n" + (Get-Content $custom -Raw) }
Set-Content -Path $target -Value $content -Encoding ASCII
Write-Host "Hosts updated: $(Get-Date)"
設定工作排程器每日/每週自動執行。
# hosts.dev → 開發環境 IP
# hosts.test → 測試環境 IP
# hosts.prod → 正式環境 IP (謹慎使用)
# 批次檔一鍵切換
copy /y C:\Hosts\hosts.dev C:\Windows\System32\drivers\etc\hosts
ipconfig /flushdns
echo Switched to DEV environment
| 問題 | 原因/說明 | 對策 |
|---|---|---|
| 修改後不生效 | DNS 快取未清、瀏覽器自有 DNS 快取 (Chrome: chrome://net-internals/#dns)、代理/VPN 繞過系統解析 | ipconfig /flushdns、瀏覽器清除快取、關閉 DoH/Proxy 測試 |
| 無法儲存/存取被拒 | 無管理員權限、防毒軟體/系統保護鎖定檔案 | 以管理員身分開啟編輯器、暫時關閉防毒即時掃描、檢查檔案屬性唯讀 |
| 通配符不支援 | Hosts 不支援 *.example.com | 需逐一列出子域名、或使用本地 DNS 伺服器 (dnsmasq/Unbound) 支援泛域名 |
| IPv6 位址格式 | 需用方括號或標準縮寫 | ::1 localhost、2001:db8::1 myserver |
| 大型 Hosts (超過 10 萬行) 導致解析變慢 | Windows 線性掃描 Hosts | 改用本地 DNS 快取伺服器 (Unbound/dnsmasq) 載入黑名單區域 |
Hosts 是最輕量、最高優先級的本地名稱解析機制。善用它可實現開發環境秒切換、內網服務好記名、系統級去廣告/防追蹤、繞過 DNS 污染。但需認清維護成本、無通配符、非動態負載均衡限制。現代最佳實踐:核心靜態映射 (內網服務) 留 Hosts,動態/大量封鎖/加速交給本地 DNS 快取 (Unbound/dnsmasq) + DoH/DoT + 瀏覽器預解析,形成分層解析架構。