Wildcard Subdomains in /etc/hosts

This post illustrates how you use a DNS forwarder to manage wildcard subdomains so that you don’t have to explicitly list each subdomain in /etc/host file.

PROBLEM

When trying to map multiple subdomains (ex: a.localhost, b.localhost, c.localhost, d.localhost) to the same IP, it is not possible to do the following in /etc/hosts:

# /etc/hosts

1.2.3.4 *.localhost

Rather, each subdomain has to be explicitly defined:

# /etc/hosts

1.2.3.4 a.localhost b.localhost c.localhost d.localhost

It requires you to babysit and manage these wildcard subdomains over time, but you do have a good job security.

SOLUTION

Configuration

Install a DNS forwarder using Homebrew.

brew install dnsmasq

Create a configuration to map the wildcard subdomains to the same IP.

sudo bash -c \
  'echo "address=/localhost/1.2.3.4" > /usr/local/etc/dnsmasq.d/localhost.conf'

Restart the service.

sudo brew services restart dnsmasq

Create /etc/resolver directory.

sudo mkdir -p /etc/resolver

Create a custom DNS resolver where the file name is the domain name.

sudo bash -c \
  'echo "nameserver 127.0.0.1" > /etc/resolver/localhost'

Verification

Flush the DNS cache first.

sudo killall -HUP mDNSResponder

Verify that ping command on each subdomain resolves to the correct IP.

$ ping -c 1 a.localhost
PING a.localhost (1.2.3.4): 56 data bytes

$ ping -c 1 b.localhost
PING b.localhost (1.2.3.4): 56 data bytes

$ ping -c 1 a.b.c.localhost
PING a.b.c.localhost (1.2.3.4): 56 data bytes