How to test localhost:PORT website by amending the hosts file

Abstract: Resolve localhost port access issues by mapping a custom domain to 127.0.0.1 via the Windows hosts file for clean URL testing.

Created: 2026-08-05 by
To test a website hosted on localhost at a specific port, you must map a custom domain name to the IP address 127.0.0.1 by editing the system hosts file. This bypasses DNS resolution and directs your browser to the local IIS instance, allowing you to access the site via http://yourdomain.com:PORT instead of the raw IP and port combination.

Understanding the Hosts File Mechanism

The hosts file is a plain text file used by operating systems to translate hostnames into IP addresses before querying external DNS servers. By adding an entry here, you create a local override that tells Windows to route traffic for a specific domain directly to your machine's loopback adapter. This technique is essential when testing web applications bound to non-standard ports or when you need a clean URL structure without exposing the port number in the address bar during development. In Windows Server environments like 2012 and 2019, as well as client OS versions paired with Visual Studio 2022, this file resides in the C:\Windows\System32\drivers\etc directory. It typically contains no extension and may be named just hosts. Because this file controls critical network routing, modifying it requires administrative privileges. Without elevated permissions, any changes will be rejected by the operating system to prevent unauthorized network manipulation.

Editing the Hosts File on Windows Server

To begin the configuration process, you must first locate the correct file path. Navigate to C:\Windows\System32\drivers\etc using File Explorer. You will see a file named hosts which might have a hidden extension depending on your view settings. Before making any edits, it is prudent to create a backup copy of this file. Rename the original to hosts.bak so you can restore the previous state if you encounter connectivity issues later. Next, open a command prompt or PowerShell window as an administrator. Right-click the Start button or search for "Command Prompt" in the taskbar, then select "Run as administrator." Alternatively, you can launch Notepad as an administrator by right-clicking the Notepad icon and selecting the same option. Once the elevated editor is open, use the File menu to open the hosts file located in the etc folder. If you opened Command Prompt, you can use the command notepad C:\Windows\System32\drivers\etc\hosts to achieve the same result within the admin context. Inside the file, scroll to the bottom and add a new line. The format is straightforward: the IP address followed by a space or tab, then the domain name you wish to use. For a localhost test on a specific port, the entry should look like this:
127.0.0.1 mytestsite.local
After saving the file, close the editor. The changes are applied immediately; however, some browsers cache DNS lookups aggressively. To ensure your browser recognizes the new mapping, clear the DNS cache or restart the browser entirely. On Windows Server, you can also flush the DNS resolver cache by running ipconfig /flushdns in the administrator command prompt.

Configuring IIS and Visual Studio Integration

With the hosts file updated, you must ensure that Internet Information Services (IIS) is configured to listen for requests directed at your new domain name. In IIS Manager, navigate to the Sites section and select your target website. Open the "Bindings" dialog from the Actions pane on the right. Here, you will see existing bindings, likely pointing to *:80: or localhost. Add a new binding for HTTP. Set the Type to http, the Port to your desired port (e.g., 8080), and crucially, set the Host name to mytestsite.local. This step binds the IIS listener specifically to the hostname defined in your hosts file. If you are using Visual Studio 2022 to develop the application, ensure that the project properties match this configuration. In the Debug settings, verify that the server URL corresponds to the new hostname and port. This setup allows you to access the site using http://mytestsite.local:8080. If you prefer not to include the port in the URL, you would need to bind the site to port 80 and configure IIS to redirect or handle the traffic accordingly, but keeping the explicit port is safer for avoiding conflicts with other services. Remember that if you change the binding in IIS, you may need to restart the IIS service using iisreset in the administrator command prompt to apply the changes fully. For more detailed guidance on hosting websites locally, refer to our guide on How to Host My Website on My Local PC: Step-by-Step Guide. Additionally, if you encounter issues where the server appears offline despite correct configurations, check our article on IIS Server Redirects to Offline Server: How to Fix Error Code 500302.

Troubleshooting Common Issues

If you cannot reach the site after these steps, several factors could be interfering. First, verify that the Windows Firewall is not blocking inbound connections on the specific port. Go to "Windows Defender Firewall with Advanced Security" and create an inbound rule allowing TCP traffic on your chosen port. Second, ensure that the IIS site status is started. A stopped site will not respond regardless of DNS configuration. Browser caching is another frequent culprit. Modern browsers store DNS records for a period known as Time to Live (TTL). Even though the hosts file overrides DNS, some browsers may still hold stale connection data. Clearing the browser cache and cookies often resolves apparent connectivity failures. Finally, check for typos in the hosts file. The domain name must match exactly what you type in the browser address bar, including case sensitivity in some contexts, though Windows is generally case-insensitive for hostnames.

Frequently Asked Questions

Do I need to restart IIS after changing the hosts file?

No, restarting IIS is not required because the hosts file affects the client-side DNS resolution, not the server-side listening sockets. However, you must restart the IIS site or run iisreset if you modify the IIS bindings to include the new hostname.

Why does my browser still show "Connection Refused"?

This error usually indicates that the firewall is blocking the port or the IIS site is not listening on that specific port. Verify your inbound firewall rules allow TCP traffic for the port and ensure the IIS binding includes the correct host name and port combination.

Can I use localhost instead of a custom domain name?

You can use localhost, but it often defaults to port 80 or 443 unless explicitly specified. Using a custom domain like mytestsite.local allows you to simulate production environments more accurately and avoids conflicts with other services that might be bound to localhost on standard ports.

Does editing the hosts file affect other users on the server?

Yes, the hosts file is a system-wide configuration. Any user account on the Windows Server instance will see the same mappings. Ensure that the changes do not conflict with other internal services or domains that rely on different IP resolutions for those hostnames.

How do I revert the changes if something breaks?

Simply delete the line you added to the hosts file or rename the backup file back to hosts. After restoring the original file, run ipconfig /flushdns to clear the cached entries and ensure your system returns to normal DNS behavior immediately.

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