Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
In Linux, /etc/hosts is a file used by the operating system to translate hostnames to IP-addresses. It is also called the ‘hosts’ file. By adding lines to this file, we can map arbitrary hostnames to arbitrary IP-addresses, which then we can use for testing websites locally.
In this tutorial, we take a look at how we can take this a step further by mapping hostnames to specific ports.
First, let’s take a look at an example. Assuming we need to map baeldung.com to 127.0.0.1, we add the following line to /etc/hosts:
127.0.0.1 baeldung.com
Now, every time we go visit the site, our OS tells the browser to visit our localhost.
Most web developers have adopted the practice to test locally using, for example, port 8080. One might wonder we can also accomplish this with /etc/hosts. For example, can we add the following line to the hosts file:
127.0.0.1:8080 baeldung.com
Unfortunately, we can’t. The hosts file only deals with hostnames, not ports.
To make it work, we can use a reverse proxy. A reverse proxy is typically a web server, like Nginx, that takes client requests and directs them to the appropriate backend server. These backend servers can run on a different host and, more interesting to us, a different port.
Let’s take a look at how to configure this with Nginx. We can easily install nginx from our package manager like yum or apt-get. Its default installation folder is /etc/nginx.
To configure a reverse proxy for baeldung.com, we add the following in a file called /etc/nginx/conf.d/baeldung.conf:
server {
listen 80;
server_name baeldung.com;
location / {
proxy_pass http://127.0.0.1:8080/;
}
}
When we use this config together with:
127.0.0.1 baeldung.com
in /etc/hosts, nginx will receive our requests for baeldung.com and direct those to the webserver running on 127.0.0.1:8080.
Mapping hostnames to IP-addresses in /etc/hosts can be very useful for testing purposes. Unfortunately, we can’t map hostnames including port numbers this way.
We have shown how to solve this issue by configuring a reverse proxy using nginx.