Hosts file
Mapping localhost to a custom domainMapping your localhost to a custom domain can be a useful trick for web development and testing purposes. It allows you
to access your local web server using a domain name rather than just "localhost" or an IP address. This article will
guide you through the process of mapping localhost to your custom domain using the /etc/hosts
file on Linux and its
Windows equivalent.
How to use /etc/hosts
(Linux/macOS)
-
To begin, open a terminal on your Linux machine. You'll need superuser privileges to modify the
/etc/hosts
file, so you may need to use thesudo
command. -
Use your preferred text editor to open the
/etc/hosts
file. For example, you can use the following command:
sudo nano /etc/hosts
- In the hosts file, you can add an entry to map your custom domain to the localhost IP address (127.0.0.1). For
example, to map
mycustomdomain.com
tolocalhost
, add the following line:
127.0.0.1 mycustomdomain.com
-
Save the file and exit your text editor.
-
Open a web browser and navigate to
http://mycustomdomain.com
. You should now see your local web server.
How to use the Hosts File (Windows)
-
Open Notepad as an administrator. To edit the hosts file on Windows, you need to run Notepad as an administrator. Right-click on the Notepad icon and choose "Run as administrator".
-
In Notepad, go to "File" > "Open" and navigate to
C:\Windows\System32\drivers\etc
. Change the file type filter to "All Files" to see the hosts file. -
Similar to Linux, add an entry to map your custom domain to the localhost IP address (127.0.0.1). For example:
127.0.0.1 mycustomdomain.com
-
Save the hosts file and close Notepad.
-
Flush DNS cache (optional). Sometimes, Windows caches DNS entries. To ensure your changes take effect immediately, open a Command Prompt as an administrator and run the following command:
ipconfig /flushdns
- Open a web browser and navigate to
http://mycustomdomain.com
. You should now see your local web server.
Conclusion
Mapping localhost to a custom domain using the /etc/hosts
file on Linux or the hosts file on Windows is a
straightforward process that can simplify web development and testing workflows. It allows you to access your local web
server using a more user-friendly domain name. Remember to remove the entry from the hosts file when you no longer need
it to avoid any conflicts with actual domain names on the internet.