1. Overview

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.

2. The hosts File

First, let’s take a look at an example. Assuming we need to map baeldung.com to, we add the following line to /etc/hosts:    baeldung.com

Now, every time we go visit the site, our OS tells the browser to visit our localhost.

3. Adding a Port Number

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:    baeldung.com

Unfortunately, we can’t. The hosts file only deals with hostnames, not ports.

4. Using a Reverse Proxy

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 / {

When we use this config together with: baeldung.com

in /etc/hosts, nginx will receive our requests for baeldung.com and direct those to the webserver running on

5. Conclusion

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.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.