Fix Permission denied when editing /etc/hosts

작성자

카테고리:

← 피드로
DEV Community · Locahl · 2026-07-17 개발(SW)

Locahl

You open the hosts file, change one line, hit save, and get Permission denied.

That is normal. The system hosts file is protected on purpose.

Why it happens

On macOS and Linux, /etc/hosts is owned by root.

On Windows, C:\Windows\System32\drivers\etc\hosts needs Administrator rights.

A normal editor process cannot overwrite it.

macOS / Linux fix

Edit with elevated rights:

sudo nano /etc/hosts

Enter fullscreen mode Exit fullscreen mode

Or open your editor as root:

sudo code /etc/hosts
# or
sudo vim /etc/hosts

Enter fullscreen mode Exit fullscreen mode

Safer pattern: edit a copy you own, then install it:

cp /etc/hosts ~/hosts.work
# edit ~/hosts.work
sudo cp /etc/hosts "/etc/hosts.bak.$(date +%Y%m%d-%H%M%S)"
sudo cp ~/hosts.work /etc/hosts

Enter fullscreen mode Exit fullscreen mode

Then flush DNS.

Windows fix

  1. Start Notepad as Administrator
  2. File → Open
  3. Go to C:\Windows\System32\drivers\etc\
  4. Set the filter to All Files
  5. Open hosts
  6. Save

If Notepad was not elevated, Windows often lets you open the file and then fails on save.

PowerShell alternative:

Start-Process notepad C:\Windows\System32\drivers\etc\hosts -Verb RunAs

Enter fullscreen mode Exit fullscreen mode

Then:

ipconfig /flushdns

Enter fullscreen mode Exit fullscreen mode

“I can edit but nothing changes”

That is a different bug:

  • you saved a copy in Downloads / Desktop
  • the line is still commented with #
  • DNS cache was not flushed
  • another line for the same hostname wins

Verify the live file:

grep -n "myapp.test" /etc/hosts

Enter fullscreen mode Exit fullscreen mode

Avoid fighting permissions every day

Keep project hosts snippets in your repo or home folder. Copy them into place with one sudo command when needed.

That keeps the protected system file boring, and your editable copy easy to version.

Quick recovery if you break hosts

You should still be able to reach the machine by IP and local loopback. Restore from your backup:

sudo cp /etc/hosts.bak.YYYYMMDD-HHMMSS /etc/hosts

Enter fullscreen mode Exit fullscreen mode

If you did not make a backup, most OS installs still have a minimal localhost block you can recreate. Do that before you go hunting for network bugs.

If you switch hosts a lot, a small desktop manager helps keep profiles and DNS flush in one place: Locahl.

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다