DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk9 min

How to Block Access to a Folder With .htaccess (Apache 2.4 Guide)

Use Apache 2.4’s Require directives to deny a folder, password-protect it, restrict it by IP, or apply conditional 403 rules. This guide covers placement, AllowOverride, TLS, legacy syntax, and troubleshooting.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To block every HTTP request to a directory on Apache 2.4, create a file named .htaccess inside that directory and add:

Require all denied

Apache describes this directive as “Access is denied unconditionally.” It returns a 403 Forbidden response when the server is reading the file and the parent configuration permits authorization directives. If the rule appears to do nothing, check the matching server-side <Directory> configuration, because .htaccess is ignored when overrides are disabled.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What the rule blocks—and what it does not

Require all denied is an Apache 2.4 authorization rule. In a directory’s .htaccess, it denies every request that reaches that directory, regardless of the visitor’s username, IP address, browser, or URL parameters. The normal result is HTTP 403 Forbidden; the file is not sent to the client.

This protects resources served through Apache’s HTTP request path. It does not encrypt files, remove them from the server, stop local users with filesystem access, or prevent another application from exposing a copy elsewhere. It also does not work if Apache never reads the file. That distinction explains most reports that an apparently correct rule is being ignored.

Put the file in the correct directory

  1. Identify the filesystem directory mapped to the URL you want to protect. For example, a URL such as https://example.test/private/report.pdf might map to /var/www/site/private.
  2. Create a plain-text file named exactly .htaccess in that mapped directory. The leading dot is part of the filename; names such as htaccess or .htaccess.txt are different files.
  3. Insert the authorization directive shown above, save the file, and request a known file or the directory URL.
  4. Confirm that Apache returns 403 Forbidden. Test from a browser and with a command-line client if possible, because a browser can display a cached page or a custom error document.

The rule applies to that directory and its descendants unless a deeper configuration changes the authorization result. It does not automatically protect a similarly named directory elsewhere in the document root.

Make sure Apache is allowed to read .htaccess

Apache decides whether to process per-directory files from the parent server configuration, normally a matching <Directory> block. A typical authorization allowance is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<Directory /var/www/site>
    AllowOverride AuthConfig
</Directory>

AuthConfig permits authentication and authorization directives such as Require, AuthType, AuthName, and AuthUserFile. The exact path in the block must cover the directory containing the .htaccess file.

If the parent configuration contains AllowOverride None, Apache does not use the file for configuration. An administrator can instead leave broad overrides disabled and allow only selected directives with AllowOverrideList. For example, a server may permit the individual Require directive without permitting every directive in the AuthConfig class. The permitted list must match the directives used in the file.

These settings cannot be enabled from inside the same ignored .htaccess file. They require access to the main Apache configuration, a virtual-host configuration, or an administrator who can change it. On managed hosting, the provider may expose an interface for this setting or may prohibit it entirely.

Choose the access policy you actually need

“Block a folder” can mean several different policies. Select the narrowest one that matches the requirement rather than combining unrelated rules.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Goal Directive pattern Who can enter Typical response
Make a directory unreachable over HTTP Require all denied Nobody 403 Forbidden
Require a username and password AuthType Basic with Require valid-user Accounts that authenticate successfully Authentication challenge, then access or 403
Allow a trusted office or subnet Require ip with an address, range, or CIDR block Matching network addresses Access or 403
Deny one address while allowing others <RequireAll> with a positive requirement and Require not ip Everyone covered by the positive rule except the denied address Access or 403
Apply a condition such as a time window mod_rewrite and the [F] flag Requests that do not trigger the condition 403 Forbidden while the condition is true

Password-protect one folder

Use HTTP Basic authentication when the directory should be available to identified users rather than blocked for everyone. The password database should be outside the document root so it cannot be downloaded as a web resource.

1. Create a password file

On a system with Apache’s bundled htpasswd utility, create the file and the first account. The -c option creates a new file and should be used only for the first account:

htpasswd -c /usr/local/apache/passwd/passwords alice

The utility prompts for the password and stores a hashed representation. To add another account later, omit -c:

htpasswd /usr/local/apache/passwd/passwords bob

Choose a location readable by the Apache process but not reachable through the site’s URL space. File ownership and permissions must allow Apache to read it while preventing unrelated local users from changing it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

2. Add authentication directives to the protected folder

Place this in the folder’s .htaccess:

AuthType Basic
AuthName "Restricted Files"
AuthBasicProvider file
AuthUserFile "/usr/local/apache/passwd/passwords"
Require valid-user

Require valid-user permits any account that successfully authenticates. To allow only named accounts, replace it with a user requirement, for example Require user alice. The path in AuthUserFile must be the actual filesystem path, not a URL.

3. Protect credentials in transit

Basic authentication encodes credentials for the HTTP authentication exchange; it does not provide confidentiality by itself. Use HTTPS/TLS for the protected directory, especially for sensitive documents or passwords. Without TLS, a network observer may recover the credentials even though the password file contains hashes.

Allow only selected IP addresses or networks

Apache 2.4 can authorize clients by IP address or host requirement. The Require ip form accepts full addresses, partial ranges, netmasks, CIDR notation, and IPv6 addresses. To allow one private subnet:

Require ip 192.168.1.0/24

To allow several networks, list multiple values in the same requirement or use a RequireAny container:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<RequireAny>
    Require ip 192.168.1.0/24
    Require ip 2001:db8:1234::/48
</RequireAny>

A host requirement can use DNS host names, but DNS-based authorization depends on name resolution and its accuracy. IP and CIDR rules are usually easier to audit when the permitted network ranges are stable.

Deny one address while allowing the rest of a network

A negated requirement cannot authorize a request on its own. Pair it with a positive requirement inside RequireAll:

<RequireAll>
    Require all granted
    Require not ip 10.252.46.165
</RequireAll>

The positive requirement establishes who may be authorized; the negated requirement removes the specified address. Writing only Require not ip 10.252.46.165 is invalid as an authorization policy because a negation by itself never grants access.

Combine requirements deliberately

RequireAny: any acceptable condition

Use RequireAny when a request may satisfy one of several independent conditions, such as a member of the office subnet or a named authenticated user:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<RequireAny>
    Require ip 192.168.1.0/24
    Require user alice
</RequireAny>

This is an “or” relationship. It does not require both conditions.

RequireAll: every positive condition, plus exclusions

Use RequireAll when conditions must be combined or when a negated condition must be attached to a positive authorization rule. Be explicit about the intended result and test each branch from a representative client.

RequireAllDenied: an explicit universal block

Require all denied is normally the clearest way to express a universal block. It avoids accidental exceptions that could arise when a broader configuration grants access elsewhere. If a parent or deeper configuration contains other authorization directives, inspect the complete authorization context before assuming the local rule is the only one being evaluated.

Block conditionally with mod_rewrite

Authorization directives are best for stable identity or network policy. For a condition such as a time window, Apache’s rewrite engine can return a forbidden response with the [F] flag:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
RewriteEngine On
RewriteCond "%{TIME_HOUR}" ">=20" [OR]
RewriteCond "%{TIME_HOUR}" "<07"
RewriteRule "^/fridge" "-" [F]

When the condition matches, Apache returns 403 Forbidden instead of serving the request. The hour is evaluated by Apache’s server time, so document the server’s timezone when the schedule matters. Adjust the rule’s URL pattern to the path as Apache sees it in the relevant per-directory context and test both sides of the boundary.

The rewrite module must be enabled, and the server must permit rewrite directives in .htaccess through the appropriate override setting. A rewrite condition based on the User-Agent header is not meaningful security: clients can change that header easily. Use authentication, network authorization, or a server-side condition when the content genuinely needs protection.

Best Value
Sale
The Web Application Hacker's Handbook: Finding and Exploiting Security Flaws
  • Comes with secure packaging
  • It can be a gift item
  • Easy to read text
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Prefer main configuration when you control Apache

A server administrator can express the same universal block in the main configuration:

<Directory /var/www/site/private>
    Require all denied
</Directory>

Central configuration is generally easier to audit and has less per-request overhead than distributing policy through many .htaccess files. It also makes the protected path and its inheritance visible in one place. Use .htaccess when you do not have access to the virtual-host or server configuration, or when a hosting arrangement intentionally delegates directory-level policy to site owners.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not put an AllowOverride directive inside .htaccess; it is valid only in the server or virtual-host configuration. If you move a working rule from .htaccess into a <Directory> block, remove the duplicate copy or document which layer is authoritative.

Troubleshoot an ignored rule or a 500 error

Symptom Likely cause What to check
The folder remains accessible Apache is not reading the file, or the file is in the wrong directory Verify the exact filename, filesystem location, URL-to-directory mapping, and the parent <Directory> block. Check for AllowOverride None or an AllowOverrideList that excludes Require.
Every request returns 500 after editing A directive is not permitted, recognized, or syntactically valid Read Apache’s error log immediately after reproducing the error. Confirm the required module is enabled and that the directive is allowed in this override context.
The rule works in one directory but not another The directories are covered by different configuration blocks Compare their parent paths, virtual hosts, inherited authorization rules, and whether each directory actually permits .htaccess.
A password prompt never succeeds Wrong password-file path, unreadable file, or account mismatch Use the absolute path in AuthUserFile, verify Apache can read the file, confirm the account was created with htpasswd, and inspect the error log.
Users receive a cached or custom page instead of the expected response Browser, proxy, or custom error handling is masking the status Inspect the actual HTTP status with a command-line client and review the site’s custom error-document configuration.
A rewrite rule has no effect mod_rewrite or its override permission is unavailable, or the pattern does not match Confirm the module and rewrite override permission, then test the pattern against the path in that directory context.

A configuration error that Apache cannot parse commonly produces a 500 Internal Server Error. An ignored file is more dangerous operationally because the site can continue serving content without an obvious error. Always inspect the error log and verify the result from an independent client after changing access policy.

Do not mix legacy and modern authorization syntax

Apache’s older access-control family uses directives such as Order, Allow, and Deny. That syntax is deprecated in current Apache 2.4 guidance and is intended mainly for compatibility configurations. The modern authorization form uses Require, RequireAll, RequireAny, and related directives.

Do not combine a legacy rule and a modern rule casually in the same directory. Mixing generations can produce confusing authorization results or require compatibility modules whose behavior is not obvious from the file. Convert the policy to one modern Require-based expression and test it after removing the old directives.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Operational and security checks

  • Protect the data at the right layer. A denied URL does not protect a second copy exposed by another virtual host, application endpoint, backup download, or direct storage service.
  • Use least privilege. Deny everyone for material that should never be web-served; use named accounts or a defined network for material that has a legitimate audience.
  • Keep password files private. Store them outside the document root, restrict filesystem permissions, and avoid putting credentials in a URL or page.
  • Use TLS for authentication. Basic authentication without HTTPS does not protect credentials from network interception.
  • Record the intended policy. Note the protected filesystem path, allowed users or networks, server timezone for scheduled rules, and the administrator responsible for the parent configuration.
  • Retest after server changes. Virtual-host edits, migrations, reverse proxies, and hosting-provider policy changes can alter whether .htaccess is read or which client IP Apache sees.

A practical decision sequence

  1. If no HTTP client should ever receive the directory, use Require all denied.
  2. If approved people need access, create an outside-document-root password file and use Basic authentication over HTTPS.
  3. If access is tied to a stable office, VPN, or subnet, use Require ip with the documented network range.
  4. If one exception must be removed from an otherwise allowed set, combine a positive requirement with a negated requirement inside RequireAll.
  5. If the condition is temporal or otherwise request-dependent, use mod_rewrite and the [F] flag, not a spoofable User-Agent test.
  6. If you administer Apache itself, place the policy in the main <Directory> configuration for centralized auditing; otherwise verify that the host permits the required .htaccess overrides.

After applying any option, test an allowed case and a denied case, check the returned status code, and read the error log if the result differs from the policy you intended.

Quick Recap

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.