Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon 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×
FREEDOM251

Freedom251 › Blog › Apache

How to Password-Protect a URL or Directory With .htaccess

By Freedom251 Team · · 11 min read

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

On Apache, password protection is applied to a directory and the URL resources Apache maps into it. Create an .htpasswd file with htpasswd, place an .htaccess file in the directory that should be restricted, and add Apache’s Basic Authentication directives. The password file should be outside the public document tree, and the site must use HTTPS because Basic Authentication does not encrypt the password in transit.

The minimum configuration

For a directory-based protection rule, create a password file and put this in the .htaccess file inside the directory mapped to the protected URL:

As an Amazon Associate I earn from qualifying purchases.

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.
AuthType Basic
AuthName "Restricted Files"
AuthBasicProvider file
AuthUserFile "/absolute/path/outside/document-root/.htpasswd"
Require valid-user

AuthType Basic selects HTTP Basic Authentication. AuthName is the realm displayed by the browser or other client. AuthBasicProvider file tells Apache to read credentials from a flat file; file is also the default provider in Apache’s example, so this line may be omitted. AuthUserFile must point to the password file using an absolute filesystem path. Require valid-user allows any account whose credentials are in that file.

This configuration protects the directory containing the .htaccess file and the resources Apache maps beneath that directory. It does not create an independent password rule for an arbitrary string in a URL. If you need to protect only one subdirectory, put the file in that subdirectory. For a site-wide or virtual-host rule, a central <Directory> block is normally preferable when you control the main Apache configuration.

What you need before changing anything

  • Apache HTTP Server: These directives are for Apache. A different web server may ignore .htaccess or use another authentication system.
  • Override support: The target directory must permit authentication directives in .htaccess. The administrator needs AllowOverride AuthConfig, or a suitable AllowOverrideList, in the applicable Apache configuration.
  • Authentication modules: Apache’s core authentication and authorization modules, including mod_authn_core and mod_authz_core, must be loaded. File authentication also requires the relevant file-provider module in the server build.
  • Filesystem access: The Apache worker process must be able to read the password file. Use permissions that permit Apache to read it without making it world-readable.
  • TLS: Use HTTPS before sending credentials. Basic Authentication itself is not encryption.

If you do not administer Apache’s main configuration, ask the host or server administrator to verify the override setting and modules. A correctly written file cannot compensate for a directory where overrides are disabled.

Step 1: Create the .htpasswd file

Apache’s htpasswd utility creates and updates the credential file. Create it outside the document root whenever possible; a browser should never be able to download it as a normal URL.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
htpasswd -c /absolute/path/outside/document-root/.htpasswd alice

The command prompts for Alice’s password and writes a hashed credential entry. The -c option creates a new file, so use it only when creating the file for the first account. To add another account to an existing file, omit -c:

htpasswd /absolute/path/outside/document-root/.htpasswd bob

Choose a path that is readable by Apache but not publicly served. If the file already exists, confirm that the command is targeting the intended file; recreating it can remove existing accounts. After creating or modifying it, check the owner and permissions and make sure the Apache process can read it.

Step 2: Put .htaccess in the directory that maps to the URL

Protect a directory

Suppose a URL such as https://example.test/private/ maps to a server directory named /srv/www/private/. Place .htaccess in /srv/www/private/ and use the authentication block shown above. Requests for files and subdirectories below that location inherit the rule unless a more specific Apache configuration changes the behavior.

The password file is not the same file as .htaccess. The latter contains Apache directives; the former contains account records and should normally live outside the document root.

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.

Protect only a subdirectory

To restrict only /members/ rather than the whole site, put the file in the directory that serves /members/. Files outside that directory are unaffected by this rule. If a parent directory already has authentication directives, the effective configuration can include both parent and child rules, so inspect the complete directory hierarchy when behavior is unexpected.

Protect a rewritten URL

URL rewriting can make a visible path differ from the filesystem location. A path such as /reports might be rewritten to a script in another directory. The .htaccess rule applies according to the directory Apache ultimately uses for the mapped resource and the server’s rewrite and directory configuration. Confirm the final mapping rather than assuming that the visible URL name alone determines the scope.

Step 3: Choose who is allowed in

The Require directive determines which authenticated accounts may proceed. Use the narrowest rule that matches the requirement.

Directive Result When to use it
Require valid-user Any account successfully authenticated by the configured provider A private area shared by all listed users
Require user alice Only the named account A resource for one specific user
Group-based authorization Only members of a configured group Separate roles, teams, or permission tiers

For a named-user rule, replace the final line with, for example:

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

Group authorization needs additional group-file and provider configuration, so do not add a group directive unless the corresponding Apache module and group data are configured. A flat file is practical for a small deployment; Apache also documents other authentication backends, including LDAP and DBM, for environments that need centralized credentials or larger-scale administration.

Allow .htaccess authentication directives

Apache reads .htaccess only when the main configuration permits it for that directory. The relevant setting is commonly:

AllowOverride AuthConfig

An administrator may instead allow only selected directives with AllowOverrideList. The setting must apply to the directory that contains the file, or to a parent directory whose configuration governs it.

If overrides are disabled, Apache may ignore the authentication directives or return an error when it encounters them. This is a server-administration issue, not a reason to make the password file public. When you control the main configuration, Apache’s own tutorial prefers moving the directives into a <Directory> block:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<Directory "/srv/www/private">
    AuthType Basic
    AuthName "Restricted Files"
    AuthBasicProvider file
    AuthUserFile "/absolute/path/outside/document-root/.htpasswd"
    Require valid-user
</Directory>

A central block avoids per-request directory-file discovery, keeps security policy in one administrative location, and does not depend on allowing users or applications to override authentication settings. The trade-off is that you need access to the virtual-host or main-server configuration and must reload or restart Apache after changing it, according to your server’s operating procedure.

Approach Scope control Administration Best fit
.htaccess Directory and descendants Can be changed without editing the main configuration, provided overrides are allowed Shared hosting or delegated directory administration
Main <Directory> block Explicit server or virtual-host filesystem path Central control; requires administrator access Managed servers where Apache configuration is available

Understand the effective protection boundary

The location of the file, not the appearance of the URL, determines the starting boundary. A file in a parent directory can cover descendants, while a file in a child directory can narrow or add to the effective rules. Aliases, virtual hosts, rewrites, and other directory settings can change which filesystem location handles a request.

For that reason, test the actual resources users will request: HTML pages, downloads, images, scripts, index files, nested directories, and rewritten routes. If a protected page loads an asset from another mapped directory, that asset may follow a different authentication rule. Conversely, a broad parent rule may prompt for credentials on more paths than intended.

A URL such as /private and the trailing-slash form /private/ can also involve directory handling and redirects. Check both forms in your deployment and verify that the final resource, rather than only the first redirect, is covered by the intended directory configuration.

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

Test the protection before relying on it

  1. Open a URL for a resource inside the protected directory over HTTPS. The client should request credentials rather than serving the resource immediately.
  2. Enter a valid account from .htpasswd and verify that the intended resource loads.
  3. Repeat with an incorrect password or an account that is not authorized by the Require rule. It should be rejected.
  4. Request a resource outside the protected directory and confirm that it remains governed by its own configuration.
  5. Test a nested directory, an index document, static assets, and any rewritten route that is supposed to be protected. A page can appear restricted while a separately mapped asset remains outside the rule’s scope.
  6. After any failure, inspect Apache’s error log while making a fresh request. The exact message is environment-specific, but it usually identifies a bad directive, an override restriction, a missing module, an unreadable password file, or an invalid path.

Test with a new private browsing session when checking the login prompt. Browsers cache Basic Authentication credentials for a session, so an earlier successful login can make a later request appear unprotected.

Fixing a 500 error or a rule that does nothing

The browser returns HTTP 500

  • Read the error log first. Do not guess; the log identifies the directive or file Apache could not process.
  • Check spelling and context. A misspelled directive or a directive not permitted in the current override context can produce a server error.
  • Verify module availability. Authentication and authorization modules must be loaded, including the core modules Apache identifies for this configuration.
  • Verify the password-file path. AuthUserFile needs an absolute filesystem path, not a URL and not a path relative to the web document.
  • Check read permissions. Apache must be able to open the file, while unrelated users should not receive unnecessary read access.

The page is still public

  • Confirm that the request is handled by Apache and that the file is named exactly .htaccess, including the leading dot.
  • Confirm that the file is in the directory Apache maps to the requested resource, not merely in a similarly named project directory.
  • Ask the administrator to verify AllowOverride AuthConfig or an appropriate AllowOverrideList.
  • Check whether a rewrite sends the request to a different directory or virtual host.
  • Review parent and child directory rules for an exception or a more specific configuration.

The login prompt appears, but valid credentials fail

  • Check the username spelling and whether the account was added to the password file you referenced.
  • Confirm that the running Apache process can read the exact file named by AuthUserFile.
  • Make sure the file was not accidentally recreated with htpasswd -c after other accounts were added.
  • Inspect the error log for provider or authorization-module errors, then test again in a fresh browser session.

Only some files are protected

Inspect the URL-to-filesystem mapping, rewrite rules, aliases, virtual-host selection, and nested directories. The protection follows Apache’s effective directory configuration, not necessarily the text displayed in the browser’s address bar.

Security limits and safer deployment

Apache explicitly warns that “Basic authentication sends the password from the client to the server unencrypted.” Use HTTPS with TLS, such as Apache’s SSL support, before presenting the login form. Without TLS, someone able to observe the connection can capture the credentials.

Basic Authentication is an access gate; it does not encrypt the protected files on disk or in transit. TLS protects the connection, while filesystem permissions protect the password file and the server’s stored data. Keep .htpasswd outside the document root whenever practical, and do not solve a permissions problem by making it world-readable.

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

Use separate accounts instead of sharing one password when you need to remove an individual’s access or audit membership. For a small, stable set of users, a file provider is simple. If credentials must be managed centrally, evaluate an LDAP, DBM, or another provider supported by your Apache installation instead of turning one flat file into an unmaintainable directory.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Operational checklist

  • Apache is serving the request.
  • The .htaccess file is in the directory that governs the resource.
  • AllowOverride AuthConfig or an appropriate AllowOverrideList is active.
  • Required authentication and authorization modules are loaded.
  • AuthUserFile uses an absolute path outside the document root.
  • The Apache process can read the password file, but it is not publicly downloadable or unnecessarily world-readable.
  • The Require rule matches the intended users or groups.
  • HTTPS is enforced before credentials are sent.
  • Valid, invalid, inside-scope, outside-scope, nested, and rewritten URLs have all been tested.
  • The error log has been checked after every 500 response or unexpected authorization result.

When to use a different design

Use a central <Directory> rule when you administer Apache and want one controlled policy. Use .htaccess when directory-level delegation is necessary and the host permits authentication overrides. Use named users or groups when “any authenticated user” is too broad. Use a non-file provider when a flat password file no longer fits your account-management needs. In every design, keep the authentication exchange behind HTTPS and verify the effective directory mapping before declaring a URL protected.

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

Frequently Asked Questions

Can I password-protect one URL without protecting a directory?

Apache’s .htaccess authentication is directory-based. Put the file in the directory that serves the resource, or use a central <Directory> rule. If a visible URL is rewritten elsewhere, verify the final filesystem mapping; the URL text alone does not define the scope.

Where should the .htpasswd file live?

Use an absolute filesystem path outside the public document root whenever possible. Apache must be able to read the file, but visitors should not be able to download it and unrelated users should not receive unnecessary read permission.

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

Why does my .htaccess file return a 500 error?

Check Apache’s error log first. Common causes are a misspelled or disallowed directive, disabled AllowOverride AuthConfig, a missing authentication module, an unreadable password file, or an invalid AuthUserFile path.

Why does the page remain public after I add authentication directives?

Confirm that Apache is serving the request, the file is named exactly .htaccess, and it is in the directory that maps to the requested resource. Then have the administrator verify AllowOverride AuthConfig or an appropriate AllowOverrideList. Rewrites, aliases, and virtual hosts can send the request to a different directory.

How do I allow only one account instead of every account in .htpasswd?

Replace Require valid-user with Require user alice. For teams or roles, use group authorization only after the corresponding group data and Apache modules are configured.

Is Basic Authentication safe without HTTPS?

No. Apache states that Basic Authentication sends the password from the client to the server unencrypted. Enable HTTPS/TLS before presenting the login challenge; Basic Authentication does not encrypt the files themselves.

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

Should I use .htaccess or a main Apache configuration block?

Use .htaccess when delegated directory-level administration is necessary and overrides are enabled. If you control Apache’s main configuration, a central <Directory> block is preferred for centralized policy and administration.

The Bottom Line

Create the account file with htpasswd, keep it outside the document root, place authentication directives in the .htaccess file governing the target directory, and confirm that AllowOverride AuthConfig and the required modules are enabled. Test every intended path over HTTPS, and use Apache’s error log whenever the rule is ignored or produces a 500 response.

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.

ApacheBasic Authenticationhtaccessserver administrationWeb Security

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.

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.