VirtualHost on-the-fly using VirtualDocumentblog_jay_sh

Let's suppose you'd like:

(In my original posting, my examples used a fictional .dev extension. This was a bad idea because gTLDs can be registered at any point, and more interestingly, .dev is now taken).

But without having to setup each VirtualHost individually, then inserting the domain into /etc/hosts. To escape this vicious circle, we can use:

  1. Apache's VirtualDocumentblog_jay_sh
  2. Dnsmasq
Apache

Create one more VirtualHost to host our VirtualDocumentblog_jay_sh:

<VirtualHost *:80>
    ServerName dev
    ServerAlias *.local.jay.sh
    UseCanonicalName Off
    VirtualDocumentblog_jay_sh /home/user/htdocs/%0
</VirtualHost>

and restart Apache (if you get an error, you may need to a2enmod vhost_alias). It's probably worth ensuring it works before jumping into DNS:

$ cat /home/user/htdocs/test.local.jay.sh/index.php
Hello from <?php echo __FILE__; ?>

$ curl localhost -H 'Host: test.local.jay.sh'
Hello from /home/user/htdocs/test.local.jay.sh/index.php</pre>
Dnsmasq

Using Dnsmasq's address option in /etc/dnsmasq.conf, we can force *.local.jay.sh to resolve to localhost

address=/.local.jay.sh/127.0.0.1

Dnsmasq will use the contents of /etc/resolv.conf
Let's confirm DNS resolution still works:

$ nslookup test.local.jay.sh localhost
Server:     localhost
Address:    127.0.0.1#53

Name:   test.local.jay.sh
Address: 127.0.0.1

$ nslookup example.com localhost
Server:     localhost
Address:    127.0.0.1#53

Non-authoritative answer:
Name:   example.com
Address: 192.0.43.10

(If you find the latter doesn't work, add server=8.8.8.8 to your /etc/dnsmasq.conf to use Google's public DNS resolvers for recursive requests.)

Setup your internet connection to use it

The final step is to set your internet connection to use it, which generally means setting your connection as 'IPv4 Addresses Only' in the properties, and setting 127.0.0.1 as the only DNS resolver.