Sometimes you may want to use a DNS server for specific domain requests and another DNS server for all other requests. This is helpful, for instance, when connected to a VPN. For hosts behind that VPN you want to use the VPN's DNS server but all other hosts you want to use Google's public DNS. This is called "DNS splitting."
Here, we run dnsmasq as a background service on macOS. The dnsmasq configuration described below implements DNS splitting.
brew install dnsmasq
Don't have Homebrew? Follow the instructions here: https://brew.sh
Add the following lines to $(brew --prefix)/etc/dnsmasq.conf:
# Ignore /etc/resolv.conf no-resolv # For queries *.domain.com and *.domain.net, forward to the specified DNS server # Servers are queried in order (if the previous fails) # -- Note: These are EXAMPLES. Replace with your desired config. server=/domain.com/domain.net/IP_ADDR_OF_SERVER1 server=/domain.com/domain.net/IP_ADDR_OF_SERVER2 # Forward all other requests to Google's public DNS server server=22.214.171.124 # Only listen for DNS queries on localhost listen-address=127.0.0.1 # Required due to macOS limitations bind-interfaces
Run the following command to start dnsmasq immediately and have it start on reboot.
sudo brew services start dnsmasq
Point macOS to the new server
To point to the new split DNS server, follow these steps:
- Open up "System Preferences," click on "Network."
- The first interface with a green ball is your default interface. Click on it and then "Advanced."
- Click on the "DNS" tab.
- Click on "+" and type in "127.0.0.1"
- Click on "OK"
- Click on "Apply"
To point to the new DNS server via scripting, run the following command (replacing "Wi-Fi" with whatever your interface name is):
sudo networksetup -setdnsservers "Wi-Fi" 127.0.0.1
To clear the DNS server change:
sudo networksetup -setdnsservers "Wi-Fi" empty
Check that hosts within each of your "server=" directives resolves as expected.
Check that hosts that do not match any "server=" directive go out to the default DNS server.
Flush DNS caches
If DNS queries are not behaving as expected, flush macOS's DNS cache.
sudo dscacheutil -flushcache sudo killall -HUP mDNSResponder