/etc/hosts File Management
Topic Overview
The /etc/hosts file is a local DNS lookup table that maps hostnames to IP addresses. It allows system administrators to override DNS resolution locally, providing faster lookups and network control without external DNS queries.
Key Concepts
- Static DNS: Local hostname-to-IP mapping
- DNS Override: Takes precedence over external DNS
- Loopback: 127.0.0.1 maps to localhost
- FQDN: Fully Qualified Domain Names supported
- IPv4/IPv6: Both address types supported
File Format
|
|
- One entry per line
- Whitespace separates fields
- Comments start with
#
File Location
- Linux/Unix:
/etc/hosts - Windows:
C:\Windows\System32\drivers\etc\hosts - Permissions: Root/admin access required
Practical Examples
Example 1: View current hosts file
|
|
Standard default entries for local system
Example 2: Add custom mapping
|
|
Maps webserver and web.local to 192.168.1.100
Example 3: Block unwanted sites
|
|
Redirects unwanted domains to nowhere
Example 4: Development environment
|
|
Local development server mappings
Use Cases
- Local Development: Test sites locally
- Network Troubleshooting: Override DNS temporarily
- Ad Blocking: Redirect unwanted domains
- Internal Networks: Map internal server names
- DNS Bypass: Quick hostname resolution
Related Commands
ping hostname - Test hostname resolution
nslookup hostname - Check DNS resolution
dig hostname - Detailed DNS lookup
host hostname - Simple hostname lookup
getent hosts hostname - System resolver lookup
File Management Commands
Backup hosts file
|
|
Edit safely
|
|
Validate entries
|
|
Tips & Troubleshooting
Common Issues:
- No effect: Check file permissions and syntax
- Typos: Validate IP addresses and hostnames
- Cache: Some apps cache DNS, restart if needed
- Order matters: First match wins
Best Practices:
- Always backup before editing
- Use comments to document entries
- Keep entries organized by purpose
- Test changes with
pingorgetent
Security Notes:
- Protect from unauthorized modification
- Monitor for malicious entries
- Regular audits recommended
- Consider file integrity monitoring
Performance:
- Large hosts files slow resolution
- Keep entries relevant and current
- Remove unused mappings regularly