Hosts file

Learn how to use the hosts file for development.

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: C:\Windows\System32\drivers\etc\hosts

On macOS or Linux, the file is located in the following folder: /etc/hosts

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.
##       localhost 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 and we want to use the hostname monprojet.test, we can just add this entry to the hosts file: monprojet.test

If we have several projects on this same server, each with its own domain, we can add each domain to this same entry: monprojet.test www.monprojet.test projet2.test www.projet2.test

Or on several lines: monprojet.test www.monprojet.test projet2.test www.projet2.test

To point to the local computer, you can use the IP address or if you have IPv6:: 1.

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!

Besoin d'aide ?

Vous ne trouvez pas ce que vous cherchez ?

Parler avec un de nos spécialistes aujourd'hui.

Par courriel

Autres suggestions