Embracing the Messiness in Search of Epic Solutions

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.


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 *.localhost

Rather, each subdomain has to be explicitly defined:

# /etc/hosts 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.



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/" > /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" > /etc/resolver/localhost'


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 ( 56 data bytes

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

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


Leave a Reply