July 16, 2020

Using a Simulated Domain Instead of localhost

I was doing a little reading into rails and subdomains. While doing this I encountered the problem of simulating an actual domain name on my local computer.

Fortunately, all it takes to do this is modififying your hosts file. Below I will show you how to do this on Linux based distributions (this should be similar for Mac I would assume, Windows I have no idea).

First, we will want to add an entry to our /etc/hosts file. We can sudo nano into that file with the following command.

# Linux
sudo nano /etc/hosts

# Mac
sudo nano /private/etc/hosts
Your host file should look something like this:

GNU nano 4.8              /etc/hosts                      localhost
::1             localhost       pop-os.localdomain      pop-os

# We will be adding this line!       lvh.me

# We could add subdomains too.       sub1.lvh.me       sub2.lvh.me

The last line is what we will want to add. This maps our local IP to lvh.me. This domain means nothing. It could be whatever you want. But, I'm using lvh.me because it seems to be more conventional. LVM = local virtual machine.

That's it! But, if you want to use this with Rails (or another software), we can do 2 different things.

We could start our rails server the standard way and just add lvh.me to that command.

rails s -p 3000 -b lvh.me

But, I'm a programmer. I want to make it even more simple.

So, what I'm going to do is write an alias for this command so that when I type "lvm" into my terminal, it will run that rails command automatically.

To do this, we will need to edit our terminal config file. Depending on if you use Bash or ZSH, this can vary.

sudo nano .bash_profile
# OR
sudo nano .bashrc
# OR
sudo nano .profile

sudo nano .zshrc

Once there, we only need to add one little line. I added a comment to it as well for neatness sake.

# Rails LVH.me alias command (lvh)
alias lvh='rails s -p 3000 -b lvh.me'

That's it! Now when I want to run my local rails server, I just type lvh into my terminal and it executes the rails s -p 3000 -b lvh.me command. Neat!

You could easily modify this a bit for other software like Sinatra, Hanami, etc.

Hope some of you find this helpful (sorry Windows users). Also, don't forget to restart your terminal for this to take effect!

tags: domains code ruby rails