localhost vs 127.0.0.1, and how to edit the hosts file
What localhost means, why 127.0.0.1 sometimes works when localhost does not, and how to make names like myapp.test.
localhost is a name that points to your own computer. You can add your own names, like myapp.test, by editing the hosts file.
What runs on Hosts file
- 127.0.0.1 is the IPv4 address that always means “this computer”
- ::1 is the same thing in IPv6
- localhost is a name that points to both. Which one your browser tries first can differ
Make your own local name
- Open the hosts file as administrator. Windows: C:\Windows\System32\drivers\etc\hosts. Mac/Linux: /etc/hosts.
- Add a line: 127.0.0.1 myapp.test.
- Save, then flush the DNS cache (commands below).
- Open http://myapp.test. Your web server must have a site for that name.
Commands you can copy
sudo nano /etc/hostsipconfig /flushdnssudo dscacheutil -flushcache; sudo killall -HUP mDNSRespondersudo resolvectl flush-cachesIf it still does not work
- Name ends in .local and loads slowly on Mac
- .local is used by Bonjour. Use .test or .localhost instead.
- Changes have no effect
- Flush DNS and restart the browser. Chrome can also cache: open chrome://net-internals/#dns and clear it.
- Can’t save the file on Windows
- Open Notepad as administrator, then open the hosts file from there.
Questions about Hosts file
- What is the difference between localhost and 127.0.0.1?
- localhost is a name that points to 127.0.0.1 (IPv4) and ::1 (IPv6). 127.0.0.1 is the IPv4 address itself.
- Which domain ending should I use for local sites?
- Use .test or .localhost. Avoid .local on macOS because it clashes with Bonjour.
Free tools that help
- Subnet calculatorEnter an IPv4 address with a prefix or netmask to get the network, broadcast, host range, wildcard mask and usable hosts. Split into subnets.
Config generators for this
- Apache virtual hostHost a website from a folder with Apache, with or without .htaccess.