Specify DNS Servers Based on Domains on macOS
A few months ago, I noticed that I couldn’t visit to any
.dev domains when using the corporation’s network. It was inconvenient, but I didn’t overthink it at that time.
However, after I encountered this situation several times, it became somehow frustrating. I asked some colleagues, and that’s when I learned that the corporation’s DNS server did something on
.dev TLD for internal use.
I tried to bypass this by changing my DNS server to Google Public DNS, but other problems were starting to show up. There were lots of internal websites that won’t be able to resolve now.
It seems I didn’t have a perfect solution:
- If I use corp’s DNS server, I won’t be able to visit these
- If I use external DNS servers like the Google ones, I won’t be able to resolve internal websites, and that’s not just
At first, I decided to use a bizarre way to solve this problem by:
Periodically resolve internal websites (using CronJob) that I frequently use with internal DNS server, write to
/etc/hosts, then set my system-wide DNS server to external ones.
It works, but weird. A former colleague even gave a confused look after he heard this.
So I started to search whether there are better solutions. Luckily enough, there is. I saw this article Use different DNS servers for different domains and gave it a try. It did work as expected, but I wasn’t sure what’s happening.
Then I checked
man 5 resolver:
Domain name associated with this resolver configuration. This option is normally not required by the Mac OS X DNS search system when the resolver configuration is read from a file in the /etc/resolver directory. In that case the file name is used as the domain name. However, domain must be provided when there are multiple resolver clients for the same domain name, since multiple files may not exist having the same name. See the SEARCH STRATEGY section for more details.
/etc/resolver/dev and wrote
nameserver 184.108.40.206 and
nameserver 220.127.116.11 solved my problem for good. Only
.dev and its subdomain uses these 2 nameservers to resolve.
You might ask: how about the internal sites using
.dev TLD? Yeah, I don’t use these so I couldn’t care less.