Debian 12 搭建 Dnsmasq 进行本地 DNS 分流
目的:不方便分流的第三方软件如 Snell 等使用内置的配置实现通过商业 DNS 去广告和部分服务的 DNS 分流(解锁)。NextDNS 和 AdGuard DNS 提供了基于 Dnsmasq 参数的 id 识别的配置,对于 Linux 服务器极其友好。
在未精简的 Debian 12 系统上,DNS 解析由 systemd-resolved
管理,因此首先禁用此服务
systemctl disable --now systemd-resolved
安装 Dnsmasq 并验证
apt update
apt install dnsmasq -y
systemctl is-enabled dnsmasq
systemctl status dnsmasq
备份 Dnsmasq 原始配置并新建配置
mv /etc/dnsmasq.conf /etc/dnsmasq.conf.bak
nano /etc/dnsmasq.conf
# === Dnsmasq Configuration File ===
# 指定 dnsmasq 监听的 IP 地址 127.0.0.1,仅供本地软件使用。
listen-address=127.0.0.1
port=53
# 忽略 /etc/resolv.conf 文件,使用本文件中定义的上游服务器。
no-resolv
# 不转发没有"."的简单域名。
domain-needed
# 过滤私有和无效的 IP 地址,增加安全性。
bogus-priv
# 为本地网络/开发环境设置一个域名
# domain=dev
# 启用主机名扩展功能
expand-hosts
# 增加 DNS 查询缓存,提高解析速度。默认是 150,建议设置为 1000 以上。
cache-size=2048
# 严格按照 server 指令的顺序进行查询。
strict-order
# --- Custom DNS Rules for ChatGPT ---
# 将所有 OpenAI/ChatGPT 相关域名指向指定的解锁 DNS。
# Using DNS 1.2.3.4 for ChatGPT related domains as requested.
server=/openai.com/1.2.3.4
server=/chatgpt.com/1.2.3.4
server=/sora.com/1.2.3.4
server=/oaistatic.com/1.2.3.4
server=/oaiusercontent.com/1.2.3.4
# --- Upstream AdGuard DNS Server Configuration ---
# 将所有其他查询发送到上游 AdGuard DNS 服务器。
server=94.140.14.49
server=94.140.14.59
add-cpe-id=<adguard_id>
# --- Optional Settings ---
# 如果需要调试,可以取消下面一行的注释来记录所有 DNS 查询。
# log-queries
# 如果需要,可以取消下面一行的注释来记录 DHCP 相关信息。
# log-dhcp
验证 Dnsmasq 配置
dnsmasq --test
重启 Dnsmasq
systemctl restart dnsmasq
将其他三方软件的 dns 设置为 127.0.0.1 即可,或者也可以让系统使用 Dnsmasq 的 DNS
nano /etc/resolv.conf
nameserver 127.0.0.1
Reference:
How to Set Up Local DNS with Dnsmasq on Debian 12
1-stream/1stream-public-utils · GitHub