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                        
127.0.0.1       localhost
::1             localhost
127.0.1.1       pop-os.localdomain      pop-os

# We will be adding this line!
127.0.0.1       lvh.me

# We could add subdomains too.
127.0.0.1       sub1.lvh.me
127.0.0.1       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.

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

# FOR ZSH
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: ruby domains rails code