Testing Subdomain-Based Applications on Localhost

Testing Subdomain-Based Applications on Localhost

A project I’m working on ran into a snag when I remembered I couldn’t point CNAME records to just any ol’ URL to an external site. Within my app, I needed to rely on routing via subdomain. The solution to working with these subdomains was actually pretty simple.

For example, photos.qneville.com is actually hosted elsewhere on PXLX, equivalent to qneville.pxlx.co.

It’s actually super easy and requires a quick modification of the hosts file. On Unix operating systems like MacOS or Linux, it’s probably easiest to modify the file directly through terminal.

$ vi /etc/hosts

I’m not really a Windows guy, but you might be able to get away with editing your hosts file with Notepad if ran as an administrator. You can find it here: C:\Windows\System32\Drivers\etc\hosts

A pure, untouched hosts file should look like this, with <ipa.ddr.ess> <alias>:

 ##
 # Host Database
 #
 # localhost is used to configure the loopback interface
 # when the system is booting. Do not change this entry.
 ##
 127.0.0.1 localhost

What this is telling you is that “http://localhost” translates directly to “http://127.0.0.1”. If you’re running a local webserver, give it a go. You can get away with spaces or tabs between the IP address and its alias.

The unfortunate part here is that you’ll need to modify your /etc/hosts file for every subdomain your test site uses. To reflect local URLs, I prefer to append a “.app” to keep that DN as FQ as possible.

For example, if your subdomains reflect user profiles, your local hosts file may look like:

##
 # Host Database
 #
 # localhost is used to configure the loopback interface
 # when the system is booting. Do not change this entry.
 ##
 127.0.0.1 localhost
 127.0.0.1 user1.mysite.app
 127.0.0.1 user2.mysite.app
 127.0.0.1 www.mysite.app

If your webserver runs on any port other than 80, you’ll need to specify it in your browser’s address bar or any other request.

eg. http://user2.mysite.app:3000

Good luck, and happy developing!

Tags: