Using Custom Domains and Multiple Localhost Ports for Applications

Abstract: Resolve localhost CORS issues and simplify debugging by mapping custom domains to specific ports using the hosts file and Nginx reverse proxy.

Created: 2026-09-25 by
To use custom domains for multiple applications on localhost, you must map specific hostnames to the loopback address in your system’s local hosts file. This allows your browser to resolve names like app1.local or app2.local to 127.0.0.1, while a local reverse proxy routes traffic to the correct port based on the Host header. When developing locally, browsers often restrict accessing resources across different ports due to same-origin policies. Running multiple services on distinct ports (e.g., React on 3000, API on 8080) makes it difficult to test integration seamlessly. By assigning each service a unique subdomain under a fake TLD like .local or .test, you create distinct origins that behave like real production environments. This approach eliminates CORS issues during development and simplifies debugging by providing clear, memorable URLs instead of cryptic port numbers. The core mechanism relies on two components: local DNS resolution via the hosts file and an HTTP reverse proxy that inspects incoming requests.

Configuring Local DNS Resolution

The first step is ensuring your operating system resolves your chosen domain names to the local machine. You do not need a real DNS server for this; the local hosts file serves as a static DNS override. This file maps hostnames directly to IP addresses before any network query occurs. On Windows, the file is located at C:\Windows\System32\drivers\etc\hosts. On macOS and Linux, it resides at /etc/hosts. You will need administrator or root privileges to edit this file. Open the file with a text editor such as Notepad++, Visual Studio Code, or nano. Add entries for each application you wish to access. For example, if you have a frontend running on port 3000 and a backend on 8080, add the following lines:
127.0.0.1 app1.local
127.0.0.1 app2.local
127.0.0.1 api.app1.local
Each line maps the hostname to the IPv4 loopback address. You can also use IPv6 (::1) if your stack supports it, but IPv4 is universally compatible. After saving the file, your OS will immediately recognize these new mappings. If you encounter stale resolutions, you may need to restart your browser or flush the DNS cache depending on your OS, but modern systems typically handle this dynamically. Avoid using complex commands that might vary by distribution; simply editing the file is the standard, reliable method.

Setting Up a Reverse Proxy

While the hosts file directs traffic to your machine, it does not know which port to use. A reverse proxy solves this by listening on standard ports (80 and 443) and forwarding requests to the appropriate local ports based on the requested hostname. Nginx is a robust, widely used choice for this task. Install Nginx via your package manager (apt install nginx on Ubuntu, brew install nginx on macOS). Create a configuration file for your local domains. In Nginx, site configurations are typically stored in /etc/nginx/sites-available/ or /etc/nginx/conf.d/. Create a file named local-dev.conf with the following structure:
server {
    listen 80;
    server_name app1.local;

    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

server {
    listen 80;
    server_name api.app1.local;

    location / {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
This configuration tells Nginx to listen for requests to app1.local and forward them to port 3000. Similarly, requests to api.app1.local go to port 8080. The proxy_set_header directives ensure that the backend applications receive the original hostname and client IP, which is crucial for logging and security headers. Enable the configuration by creating a symbolic link to the sites-enabled directory or including it in the main Nginx config. Restart Nginx to apply changes.

Handling TLS and Certificates

In production, HTTPS is mandatory, and browsers enforce strict security policies against mixed content. Testing with plain HTTP works for basic functionality, but many modern APIs and features require secure contexts. Generating valid SSL certificates for local domains is challenging because public Certificate Authorities do not issue certs for arbitrary local names. Instead, you can use mkcert, a tool designed specifically for local development. Install mkcert and create a local trust authority. Run mkcert -install to generate a CA certificate and add it to your system’s trusted store. Then, generate certificates for your domains: mkcert app1.local api.app1.local. This creates app1.local.pem and app1.local-key.pem. Update your Nginx configuration to listen on port 443 and include these certificate files. Ensure your hosts file still points to 127.0.0.1 so the DNS resolution remains local. This setup provides a fully functional HTTPS environment without triggering browser security warnings. For more details on handling TLS connections with unknown CAs, see our guide on establishing secure connections when certificates are not recognized by default stores. This is particularly relevant when testing mobile devices on the same network, as they may not trust the local mkcert CA unless explicitly installed.

Verifying Your Setup

Once configured, open your browser and navigate to http://app1.local. You should see the application served from port 3000. Navigate to http://api.app1.local to verify the backend is accessible. Check the browser console for any CORS errors; since both subdomains share the same base name and origin scheme, they are treated as same-origin by most browsers, eliminating cross-origin restrictions. If you experience connectivity issues, verify that Nginx is running and that no other service is blocking ports 80 or 443. Use curl -I http://app1.local to inspect response headers and confirm the proxy is working correctly.

Frequently Asked Questions

Why not just use 127.0.0.1:3000 and 127.0.0.1:8080?

Using direct port access prevents testing cross-domain scenarios and triggers browser security warnings for APIs called from different origins. Custom domains allow you to simulate production-like conditions where cookies, storage, and authentication tokens are scoped to specific domains.

Do I need to restart my computer after editing the hosts file?

No, restarting your computer is unnecessary. Modern operating systems reload the hosts file instantly upon save. However, you may need to restart your web browser or clear its DNS cache to see the changes immediately, especially if you previously visited those URLs.

Can I use this method on a mobile device connected to the same Wi-Fi?

Yes, but you must configure your router or use a tool like ngrok to expose your local Nginx instance. Additionally, the mobile device must trust the local CA certificate generated by mkcert. Without trusting the CA, the browser will block HTTPS connections due to invalid certificates.

What happens if I want to add another application later?

Simply add a new entry to your hosts file and a new server block in your Nginx configuration. There is no limit to the number of domains you can define, provided your machine has enough memory and CPU to handle the concurrent processes.

Is it safe to use .local as a TLD?

Using .local is generally safe for local development, but be aware that mDNS (Multicast DNS) uses the .local namespace. On some networks, this can cause conflicts if multicast DNS is enabled. Using .test or .dev is recommended as these are reserved for documentation and testing by IANA, ensuring no conflict with real internet domains.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More