How to use a domain name for local development
Suppose you want to use a domain for development on your local server. You have a virtual machine (maybe Vagrant) or a server that you will be programming on. If you want to reach this server using the domain monprojet.test, how would you do that?
Well, we can't create or buy this domain (as far as I know the .test TLD doesn't exist yet ...). If we could, we would have to spend some money (which sucks) and then manage the DNS for the domain, pointing the domain to the correct IP address.
If we type http://monprojet.test in our browser, the browser will not know what to do with it! No mechanism is in place to tell the browser which IP address the domain should resolve to.
We need a way to tell the browser that the domain monprojet.test is pointing to an IP address. Fortunately, all computers (in all operating systems) have a hosts file. This file allows us to map domains to IP addresses.
On Windows, the file is located in the following folder:
On macOS or Linux, the file is located in the following folder:
This is a text file and therefore can be edited by your preferred editor. However, you need to have administrator or root access to be able to modify the file. On Windows you can run software like notepad as administrator before opening the file.
On macOS or Linux, you can run the following command:
sudo nano /etc/hosts
The contents of the file usually look like this:
Note that although we have a separate development server, we are modifying the hosts file on the computer where we want to use the monprojet.test domain. We do not edit the server (or virtual machine) hosts file.
On my Mac it looks like this:
## # 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 255.255.255.255 broadcasthost ::1 localhost
How do we use this file to point a domain to our server? Fortunately, it is easy! If our development server is at the IP address 192.168.22.10 and we want to use the hostname monprojet.test, we can just add this entry to the hosts file:
If we have several projects on this same server, each with its own domain, we can add each domain to this same entry:
192.168.22.10 monprojet.test www.monprojet.test projet2.test www.projet2.test
Or on several lines:
192.168.22.10 monprojet.test 192.168.22.10 www.monprojet.test 192.168.22.10 projet2.test 192.168.22.10 www.projet2.test
To point to the local computer, you can use the IP address
127.0.0.1 or if you have IPv6
After you save your file (and sometimes after clearing your computer's DNS cache), you'll find that these domains start working - you can type them into your browser. Domains will be resolved to the IP address you set!