Skip to main content

How to Block a Website by Adding it to the Hosts File in Batch Script

Blocking websites using the Windows Hosts file is an effective, low-level method to restrict access to specific domains without additional software or firewall rules. By mapping a domain name to a non-routable IP address (0.0.0.0 or 127.0.0.1), the browser cannot reach the external server, i.e. the connection fails instantly. Automating this with a Batch script allows rapid deployment, easy toggling, and consistent application across machines.

This guide explains how to build a professional website blocking script with proper validation, duplicate prevention, and unblocking capability.

How Hosts File Blocking Works

Normal DNS resolution:
Browser → "www.example.com" → DNS Server → 93.184.216.34 → Website loads

With hosts file block:
Browser → "www.example.com" → Hosts file → 0.0.0.0 → Connection fails
(DNS server never contacted)

The hosts file is checked BEFORE any DNS server. When a blocked domain is found in the hosts file pointing to 0.0.0.0, the connection drops immediately, i.e. the DNS server is never queried.

0.0.0.0 vs. 127.0.0.1 for blocking:

Block IPBehaviorSpeed
0.0.0.0Request is dropped: no connection attemptFastest (immediate failure)
127.0.0.1Redirects to localhost: TCP connection attempt then rejectionSlightly slower

Both effectively block the domain. 0.0.0.0 is preferred because the system recognizes it as "no destination" and fails instantly, without attempting a TCP handshake.

Administrative Privileges Required

The drivers\etc folder is a protected system directory. Any script that modifies the Hosts file MUST be run as Administrator. Without elevation, the echo >> command fails silently or with "Access Denied."

Method 1: Block a Single Website

Blocks a specific domain with duplicate checking, both root and www variants, and DNS cache flushing.

Implementation

@echo off
setlocal

set "Domain=%~1"
set "BlockIP=0.0.0.0"
set "HostsFile=%SystemRoot%\System32\drivers\etc\hosts"

if "%Domain%"=="" (
echo Usage: %~nx0 ^<domain^>
echo.
echo Blocks a website by adding it to the hosts file.
echo Both the root domain and www subdomain are blocked.
echo.
echo Examples:
echo %~nx0 distracting-site.com
echo %~nx0 social-media.example.com
endlocal
exit /b 1
)

:: Verify admin privileges
net session >nul 2>&1
if errorlevel 1 (
echo [ERROR] Blocking websites requires administrator privileges. >&2
echo Right-click and select "Run as administrator." >&2
endlocal
exit /b 1
)

:: Normalize: strip "www." prefix if provided (we'll add both variants)
set "BaseDomain=%Domain%"
if /i "%Domain:~0,4%"=="www." set "BaseDomain=%Domain:~4%"

echo [INFO] Blocking: %BaseDomain% (and www.%BaseDomain%)
echo.

:: Clear read-only attribute if set
attrib -r -s -h "%HostsFile%" >nul 2>&1

:: Create backup
copy "%HostsFile%" "%HostsFile%.bak" >nul 2>&1

set "Added=0"

:: Block root domain
findstr /i /c:"%BaseDomain%" "%HostsFile%" | findstr /c:"%BlockIP%" | findstr /v /r "^#" >nul 2>&1
if errorlevel 1 (
:: Check for conflicts (different IP)
findstr /i /c:" %BaseDomain%" "%HostsFile%" | findstr /v /r "^#" >nul 2>&1
if not errorlevel 1 (
echo [WARNING] %BaseDomain% already exists with a different IP: >&2
findstr /i /c:" %BaseDomain%" "%HostsFile%" | findstr /v /r "^#"
echo.
)

echo %BlockIP% %BaseDomain% >> "%HostsFile%"
echo [BLOCKED] %BaseDomain%
set /a "Added+=1"
) else (
echo [SKIP] %BaseDomain% (already blocked^)
)

:: Block www variant (if different from base)
if /i not "%BaseDomain%"=="www.%BaseDomain%" (
findstr /i /c:"www.%BaseDomain%" "%HostsFile%" | findstr /c:"%BlockIP%" | findstr /v /r "^#" >nul 2>&1
if errorlevel 1 (
echo %BlockIP% www.%BaseDomain% >> "%HostsFile%"
echo [BLOCKED] www.%BaseDomain%
set /a "Added+=1"
) else (
echo [SKIP] www.%BaseDomain% (already blocked^)
)
)

:: Re-apply read-only attribute
attrib +r "%HostsFile%" >nul 2>&1

echo.

if %Added% gtr 0 (
:: Flush DNS cache
ipconfig /flushdns >nul 2>&1
echo [OK] %Added% entry(ies) added. DNS cache flushed.
) else (
echo [INFO] No changes needed - domain was already blocked.
)

endlocal
exit /b 0
Why Block Both Root and www

example.com and www.example.com resolve independently via DNS. Blocking only one leaves the other accessible. Most websites redirect between the two, so blocking both ensures complete coverage:

0.0.0.0 example.com
0.0.0.0 www.example.com

Why the space before the domain in the conflict check:

The search findstr /i /c:" %BaseDomain%" (with a leading space) helps avoid partial matches. Without the space, searching for site.com would also match mysite.com. The space ensures the match begins at a word boundary after the IP address. This is not foolproof (tabs are also valid separators), but catches the most common format.

Method 2: Block Multiple Websites from a List

For blocking multiple domains (ad trackers, distracting sites, or known malicious domains) maintain a list and apply them all in one pass.

Block list file (block_list.txt):

# Distracting sites
social-media.example.com
video-streaming.example.com
gaming-platform.example.com

# Ad trackers
ads.tracker-network.com
analytics.ad-company.com
pixel.tracking-service.net

Implementation

@echo off
setlocal EnableDelayedExpansion

set "BlockList=%~1"
set "BlockIP=0.0.0.0"
set "HostsFile=%SystemRoot%\System32\drivers\etc\hosts"

if "%BlockList%"=="" (
echo Usage: %~nx0 ^<block_list_file^>
echo.
echo Blocks all domains listed in the specified file.
echo File format: one domain per line. Lines starting with # are ignored.
echo.
echo Example: %~nx0 block_list.txt
endlocal
exit /b 1
)

net session >nul 2>&1
if errorlevel 1 (
echo [ERROR] Administrator privileges required. >&2
endlocal
exit /b 1
)

if not exist "%BlockList%" (
echo [ERROR] Block list file not found: %BlockList% >&2
endlocal
exit /b 1
)

:: Clear attributes and create backup
attrib -r -s -h "%HostsFile%" >nul 2>&1
copy "%HostsFile%" "%HostsFile%.bak" >nul 2>&1

echo [INFO] Applying block list from: %BlockList%
echo.

set "Added=0"
set "Skipped=0"

:: Add a separator comment
echo. >> "%HostsFile%"
echo # Block list applied by %USERNAME% on %date% >> "%HostsFile%"

:: Process each domain in the list
for /f "usebackq tokens=* eol=#" %%d in ("%BlockList%") do (
set "Domain=%%d"

:: Skip empty lines
if not "!Domain!"=="" (
:: Check if already blocked
findstr /i /c:"!Domain!" "%HostsFile%" | findstr /c:"%BlockIP%" | findstr /v /r "^#" >nul 2>&1
if errorlevel 1 (
echo %BlockIP% !Domain! >> "%HostsFile%"
echo [BLOCKED] !Domain!
set /a "Added+=1"
) else (
echo [SKIP] !Domain!
set /a "Skipped+=1"
)
)
)

attrib +r "%HostsFile%" >nul 2>&1

echo.
echo [DONE] Added: !Added! Skipped: !Skipped!

if !Added! gtr 0 (
ipconfig /flushdns >nul 2>&1
echo [OK] DNS cache flushed. Blocks are active.
)

endlocal
exit /b 0

Why eol=# in the for /f:

The eol=# parameter tells for /f to treat lines starting with # as comments and skip them. This allows the block list file to include documentation and section headers.

Hosts File Size Limit

The hosts file is read sequentially for every DNS lookup on the machine. Very large hosts files (thousands of entries) can measurably slow DNS resolution. For blocking hundreds or thousands of domains, use DNS-level solutions instead:

  • Pi-hole: Network-wide DNS sinkhole
  • Windows DNS Policy: Group Policy-based DNS filtering
  • Firewall rules: Block by IP or domain at the network level

The hosts file is best suited for blocking up to a few dozen domains.

Method 3: Unblock a Website

Blocking is only useful if you can unblock when needed. This method removes the block entries for a specific domain.

@echo off
setlocal

set "Domain=%~1"
set "HostsFile=%SystemRoot%\System32\drivers\etc\hosts"

if "%Domain%"=="" (
echo Usage: %~nx0 ^<domain^>
echo.
echo Removes the block for a website from the hosts file.
echo.
echo Example: %~nx0 social-media.example.com
endlocal
exit /b 1
)

net session >nul 2>&1
if errorlevel 1 (
echo [ERROR] Administrator privileges required. >&2
endlocal
exit /b 1
)

:: Normalize
set "BaseDomain=%Domain%"
if /i "%Domain:~0,4%"=="www." set "BaseDomain=%Domain:~4%"

:: Check if the domain is actually blocked
findstr /i /c:"%BaseDomain%" "%HostsFile%" >nul 2>&1
if errorlevel 1 (
echo [INFO] %BaseDomain% is not in the hosts file. Nothing to unblock.
endlocal
exit /b 0
)

echo [INFO] Entries to remove:
findstr /i /c:"%BaseDomain%" "%HostsFile%"
echo.

set /p "Confirm=Unblock %BaseDomain%? (YES/no): "
if /i not "%Confirm%"=="YES" (
echo [INFO] Cancelled.
endlocal
exit /b 0
)

:: Backup
attrib -r -s -h "%HostsFile%" >nul 2>&1
copy "%HostsFile%" "%HostsFile%.bak" >nul 2>&1

:: Remove entries containing the domain
set "TempFile=%TEMP%\hosts_unblock_%RANDOM%.txt"
findstr /v /i /c:"%BaseDomain%" "%HostsFile%" > "%TempFile%"
copy /y "%TempFile%" "%HostsFile%" >nul 2>&1

if errorlevel 1 (
echo [ERROR] Failed to update hosts file. >&2
copy /y "%HostsFile%.bak" "%HostsFile%" >nul 2>&1
del "%TempFile%" 2>nul
attrib +r "%HostsFile%" >nul 2>&1
endlocal
exit /b 1
)

del "%TempFile%" 2>nul
attrib +r "%HostsFile%" >nul 2>&1

echo [OK] %BaseDomain% has been unblocked.

ipconfig /flushdns >nul 2>&1
echo [OK] DNS cache flushed. The site should be accessible now.

endlocal
exit /b 0
Why unblocking is essential

A blocking script without an unblocking counterpart forces manual hosts file editing to undo the block, i.e. error-prone and frustrating. Providing both scripts makes the blocking system a complete, manageable tool.

Method 4: List Currently Blocked Domains

View all domains currently blocked in the hosts file.

@echo off
setlocal

set "HostsFile=%SystemRoot%\System32\drivers\etc\hosts"

echo [INFO] Currently blocked domains:
echo --------------------------------------------------
echo.

:: Find active entries pointing to 0.0.0.0 or 127.0.0.1 (blocking IPs)
set "Count=0"
for /f "tokens=1-2" %%a in ('findstr /v /r "^#" "%HostsFile%" ^| findstr /r "^0\.0\.0\.0 ^127\.0\.0\.1"') do (
:: Skip localhost entries
echo %%b | findstr /i "localhost" >nul 2>&1
if errorlevel 1 (
echo %%b
set /a "Count+=1"
)
)

echo.

if %Count% equ 0 (
echo (No blocked domains found)
) else (
echo Total: %Count% domain(s) blocked
)

echo.
echo --------------------------------------------------

endlocal
exit /b 0

Sample output:

social-media.example.com
www.social-media.example.com
ads.tracker-network.com
analytics.ad-company.com

Total: 4 domain(s) blocked

How to Avoid Common Errors

Wrong Way: Using > Instead of >>

:: CATASTROPHIC: overwrites the ENTIRE hosts file with a single line
echo 0.0.0.0 website.com > C:\Windows\System32\drivers\etc\hosts

A single > creates a new file containing only the echoed line. All other hosts file entries, including localhost definitions, are destroyed. This can break local networking and application configurations.

Correct Way: Always use >> (append) to add lines to the hosts file:

echo 0.0.0.0 website.com >> "%HostsFile%"
The > vs. >> Distinction Is Critical

This is the single most destructive mistake possible when editing the hosts file. A single > destroys the entire file contents. Always double-check that you're using >> (append) and never > (overwrite) when writing to the hosts file.

Wrong Way: Blocking Only One Variant of the Domain

:: INCOMPLETE: www.example.com is still accessible
echo 0.0.0.0 example.com >> hosts

Correct Way: Block both the root domain and the www subdomain:

echo 0.0.0.0 example.com >> "%HostsFile%"
echo 0.0.0.0 www.example.com >> "%HostsFile%"

Method 1 handles this automatically.

Problem: Antivirus Blocks Hosts File Modification

Many antivirus products (Norton, Malwarebytes, Kaspersky) monitor the hosts file because malware commonly uses it to redirect banking and security sites. Your script may run without errors but the file remains unchanged because the AV silently reverted the change.

Solution: Check your antivirus settings for "Hosts File Protection" and either whitelist your management script or temporarily disable the protection during the modification.

Antivirus Interference

If your script reports success but findstr shows the entry was not actually added, check your antivirus logs. The AV may be silently reverting hosts file changes. This is a security feature, not a bug, i.e. the AV is protecting against the same technique that malware uses.

Problem: Browser Has Its Own DNS Cache

After modifying the hosts file and flushing the Windows DNS cache with ipconfig /flushdns, the browser may still access the blocked site using its internal DNS cache.

Solution: After blocking, if the site is still accessible:

  1. Close and reopen the browser.
  2. In Chrome: navigate to chrome://net-internals/#dns and click "Clear host cache."
  3. In Firefox: navigate to about:networking#dns and click "Clear DNS Cache."
  4. In Edge: navigate to edge://net-internals/#dns and click "Clear host cache."

Problem: HTTPS Sites May Show Certificate Errors Instead of Failing

When blocking with 127.0.0.1, HTTPS sites may show a certificate error page rather than failing to load, because the browser connects to localhost and receives an invalid certificate response. With 0.0.0.0, the connection fails immediately with no page at all.

Solution: Use 0.0.0.0 for cleaner blocking behavior (all methods in this guide use 0.0.0.0 by default).

Best Practices and Rules

1. Always Use >> (Append), Never > (Overwrite)

This cannot be emphasized enough. A single > destroys the entire hosts file.

2. Always Check for Duplicates Before Adding

Running a blocking script multiple times without duplicate checking creates redundant entries. All methods in this guide check for existing entries first.

3. Block Both Root and www Variants

example.com and www.example.com are independent DNS entries. Block both for complete coverage.

4. Always Flush DNS After Changes

ipconfig /flushdns clears the Windows DNS resolver cache. Without it, the block may not take effect for minutes.

5. Provide an Unblocking Mechanism

Every blocking script should have a corresponding unblocking script (Method 3). Blocks without a documented removal process become permanent obstacles.

6. Handle File Attributes

Some systems have the hosts file set to read-only. Clear attributes before writing, re-apply after:

attrib -r -s -h "%HostsFile%" >nul 2>&1
:: ... modify ...
attrib +r "%HostsFile%" >nul 2>&1

7. Use DNS-Level Solutions for Large-Scale Blocking

The hosts file is appropriate for blocking up to a few dozen domains. For hundreds or thousands (ad blocking, content filtering), use network-level DNS filtering (Pi-hole, DNS policies, firewall rules).

Conclusion

Blocking websites via the hosts file is a fast, effective technique for managing access on individual machines. By handling both domain variants (root and www), checking for duplicates, managing file attributes, flushing DNS, and providing an unblocking counterpart, you create a complete, professional blocking system. Remember that the hosts file is a local-only tool, i.e. blocks apply only to the machine where the file is modified, and that antivirus software may interfere with hosts file changes as a security measure.