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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

To password-protect an Apache directory on Ubuntu, install the apache2-utils package, create an .htpasswd credential file outside the web root, and add Apache Basic Authentication directives in the directory or virtual-host configuration. If you use .htaccess, the matching Apache <Directory> block must allow authentication overrides with AllowOverride AuthConfig. Always serve Basic Authentication over HTTPS because the password is otherwise sent without transport encryption.

What Apache Basic Authentication does

Apache Basic Authentication protects a URL path by challenging a client for a username and password. Apache checks the submitted username against a flat credential file created with htpasswd. A successful match allows the request to continue; an unauthenticated request receives an HTTP 401 challenge. The mechanism is simple and widely supported, but it is not a complete security system by itself. The password must travel through a properly configured HTTPS connection, and both the credential file and the protected directory need suitable filesystem permissions.

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

The setup has two independent parts:

  • Credentials: an .htpasswd file containing password records managed by htpasswd.
  • Authorization policy: Apache directives that select Basic Authentication, identify the credential file, and state which users may enter.

Keeping those parts separate makes troubleshooting easier. A valid credential file does nothing until Apache reads it through an active configuration block, and correct directives cannot authenticate anyone if Apache cannot read the file.

Prerequisites and a safe layout

You need an Ubuntu server with Apache installed, administrative access through sudo, and a directory you intend to restrict. The examples use /var/www/html/private as the protected directory and https://example.com/private/ as its URL. Replace those values with the path and hostname used by your virtual host.

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.

Place the password file outside the document root and outside Apache’s URI space. The example path /etc/apache2/.htpasswd is preferable to /var/www/html/.htpasswd, because a file under the document root can be accidentally exposed by an alias, a misrouted request, a backup copy, or a future configuration change. Apache’s documentation specifically advises keeping web password files where browsers cannot fetch them.

The account that runs Apache must be able to read the credential file, while ordinary web visitors must never be able to request it as a URL. Use the narrowest ownership and permission policy that fits your server’s administration model; do not make the file world-readable merely to work around a permission error.

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

Install the htpasswd utility

Ubuntu supplies htpasswd in the apache2-utils package. Install it before creating accounts:

sudo apt update
sudo apt install apache2-utils

The package contains the utility used to create and update the flat file consumed by Apache’s file authentication provider. Installing it does not by itself protect a directory; the Apache configuration still has to reference the resulting file.

Create and manage the credential file

Create the file and its first user

Create a new file with the -c option and choose the first username. The command prompts for the password without displaying it:

sudo htpasswd -c /etc/apache2/.htpasswd alice

Enter the password twice when prompted. The command writes an entry for alice to /etc/apache2/.htpasswd. Use an absolute filesystem path so there is no ambiguity about which file Apache should read.

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

Add additional users

When the file already exists, omit -c:

sudo htpasswd /etc/apache2/.htpasswd bob

This adds or updates bob while preserving the other records. Running htpasswd -c again against an existing path can replace the file, removing accounts that were already present. Treat -c as a one-time creation option, not as a general add-user switch.

Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth

Limit access to one named account

The file may contain several users, while a particular directory can allow only selected names. Later, use Require user alice in the Apache policy when only Alice should be accepted. Use Require valid-user when every username with a valid record may enter.

Protect the file operationally

Keep the file in /etc/apache2 or another directory outside the served tree, include it in your server’s protected configuration backups, and restrict who can edit it. A person who can replace the file can add an account or change an existing password, so file integrity matters as much as read access. If you discover that the file is downloadable or reachable through a URL, move it immediately, update AuthUserFile, and reload Apache after validating the new configuration.

Preferred method: configure a directory or virtual host

Central Apache configuration is normally the better administrative choice. It keeps the policy with the virtual host or directory definition, makes changes visible to administrators, and avoids depending on a separate per-directory file. Add a block matching the filesystem directory that maps to the protected URL:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<Directory "/var/www/html/private">
    AuthType Basic
    AuthName "Restricted area"
    AuthBasicProvider file
    AuthUserFile "/etc/apache2/.htpasswd"
    Require valid-user
</Directory>

What each directive means

  • AuthType Basic selects HTTP Basic Authentication.
  • AuthName "Restricted area" supplies the authentication realm shown by clients in a login prompt. Keep the wording meaningful to users who may see it.
  • AuthBasicProvider file tells Apache to use a flat file provider. Apache documents file as the default provider for Basic Authentication, so this line is optional when that default is intended; leaving it explicit makes the configuration easier to audit.
  • AuthUserFile "/etc/apache2/.htpasswd" gives Apache the absolute path to the credential file. It is a filesystem path, not a URL and not a path relative to the document root.
  • Require valid-user authorizes any username whose password validates against the file.

Allow only a named user

Replace the final line when the directory is for one account:

Require user alice

You can use the same form for a specifically permitted account rather than granting access to everyone listed in the file. Keep the credential record and the authorization rule consistent; adding a person to .htpasswd does not automatically grant access to a directory restricted with Require user.

Choose the correct configuration block

The <Directory> path must correspond to the actual directory Apache serves. A block for /var/www/html/private will not protect content stored in a different path merely because the URL also contains the word private. If the site uses a virtual host, place the block where that host’s configuration is maintained and ensure no later, more specific rule changes the effective policy.

Alternative method: use .htaccess

.htaccess is useful when directory owners need to change access rules without editing the main virtual-host configuration. Create /var/www/html/private/.htaccess with the authentication directives:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black | LED mouse pad with 14 lighting modes, covers keyboard & mouse, anti-slip rubber base, waterproof surface, USB powered
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.
AuthType Basic
AuthName "Restricted area"
AuthBasicProvider file
AuthUserFile "/etc/apache2/.htpasswd"
Require valid-user

The file still uses the same credential store and the same authorization semantics as the central configuration. The crucial difference is that Apache must be told to accept authentication directives from that directory’s .htaccess file.

Permit authentication overrides

In the active Apache configuration, add or adjust the matching directory block:

<Directory "/var/www/html/private">
    AllowOverride AuthConfig
</Directory>

AllowOverride AuthConfig permits authentication-related directives in .htaccess. Without an appropriate override setting, Apache can ignore or reject the directives, making the file appear ineffective. A broader override policy may also permit them, but it gives directory-level files authority over more configuration categories and therefore increases the chance of accidental changes. Use the narrowest setting that supports the directives you need.

Central configuration versus .htaccess

Decision point <Directory> or virtual host .htaccess
Administration Centralized with the server or site configuration Delegated to a file in the served directory
Override requirement No AllowOverride permission is needed for the directives in the central block The matching directory must allow authentication overrides, such as AllowOverride AuthConfig
Change workflow Validate and reload Apache after editing the active configuration Apache reads the file as requests are processed, but the enclosing override policy must already allow it
Operational risk Less likely to be hidden in a content directory; a syntax error is found during configuration testing Convenient for delegated administration, but easy to place in the wrong directory or disable through an override rule
Authentication directives Both methods use AuthType, AuthName, AuthUserFile, a file provider, and a Require rule

Do not configure the same directory in both places unless you have a specific reason and understand which directives are inherited or overridden. Duplicate policies make it harder to identify the rule that is actually denying or granting a request.

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

Validate the configuration and apply it

Always test syntax before reloading the service:

sudo apache2ctl configtest

A successful test should report that the syntax is acceptable. If it reports an error, correct that error before attempting a reload. Common causes include a misspelled directive, an unclosed configuration block, an invalid path, or an authentication directive being read in a context where it is not allowed.

After a successful test, reload Apache so it adopts the change without unnecessarily stopping the service:

sudo systemctl reload apache2

Service-management behavior can vary with the installed Ubuntu release and the server’s unit configuration. If the reload fails, inspect Apache’s error log, rerun apache2ctl configtest, and verify that the edited file is included by the active virtual host. Check the absolute AuthUserFile path, its permissions, and the directory path in the relevant <Directory> block.

Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.

Test the challenge and successful login

Check the unauthenticated response

Request the protected URL without credentials:

curl -I https://example.com/private/

An unauthenticated request should receive a 401 response and an authentication challenge. If you receive a normal 200 response, the request may be reaching a different virtual host or URL path, the configuration may not have loaded, or the requested resource may not be inside the protected directory.

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

Supply a credential interactively

Test a known account with:

curl -u alice https://example.com/private/

curl prompts for Alice’s password rather than putting it in the shell history. Valid credentials should return the protected resource. Use HTTPS for this test whenever the site is intended to handle real passwords; testing over plain HTTP can expose the credential in transit.

Test each authorization case

  • Request without credentials and confirm the 401 challenge.
  • Use an incorrect password and confirm that access is denied.
  • Use a valid password for a listed user and confirm access.
  • If using Require user alice, test another valid file user and confirm that the named-user restriction works.
  • Request a neighboring, intentionally public directory to ensure the rule is not broader than intended.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common failures

“Invalid command ‘AuthType’” or a similar directive error

This usually means Apache is reading the directive in a context where authentication overrides are not permitted, or the required authentication modules are unavailable. For a central configuration, move the directives into a valid virtual-host or <Directory> context. For .htaccess, verify that the matching directory allows AuthConfig overrides. Confirm that the installed Apache modules provide Basic Authentication, file-based user lookup, and authorization support, then run apache2ctl configtest again.

.htaccess appears to be ignored

Check all of the following in order:

  1. Confirm the file is named exactly .htaccess and is located in the directory that maps to the requested URL.
  2. Confirm the active configuration has a matching <Directory> block.
  3. Set AllowOverride AuthConfig in that block, then validate and reload Apache.
  4. Verify that the request is reaching the expected virtual host rather than another site definition.
  5. Review the error log for a rejected directive or a permissions failure.

A correctly written .htaccess file has no effect when Apache’s enclosing directory policy disallows its directives.

Login prompts repeat indefinitely

Repeated prompts indicate that the server is not accepting the submitted credentials. Recheck the username and password, the exact realm shown by the client, and the absolute AuthUserFile path. Confirm that the file contains the intended account and that Apache can read it. If you recently moved the file, update every configuration reference and reload Apache. Test with curl -u alice to remove browser autofill and cached-credential behavior from the diagnosis.

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

Every valid user receives 403 Forbidden

A 403 response after authentication usually points to the authorization rule or filesystem access to the target directory. Verify whether the policy says Require user alice while you are testing another account, or whether a different Require rule is active. Then check that Apache can traverse and read the protected directory and its files. A successful password check does not override ordinary filesystem permissions.

The credential file is downloadable

Treat this as an exposure, not merely a cosmetic configuration issue. Move the file outside the document root and URI space, change AuthUserFile to the new absolute path, protect the file’s ownership and permissions, validate the configuration, and reload Apache. Consider any passwords in the exposed file compromised and replace the affected accounts according to your site’s incident procedure.

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.

Reload fails after an edit

Run sudo apache2ctl configtest and read the exact line reported. Check quotation marks, block delimiters, directive spelling, and whether the file path exists. If the error concerns an authentication directive, revisit its context and the AllowOverride setting. Apache’s error log can identify a missing file, unreadable credential store, or module problem that a syntax check alone cannot reveal.

Security requirements for Basic Authentication

Use HTTPS, not plain HTTP

Apache’s official guidance states that Basic Authentication sends the password from the client to the server unencrypted. The password is encoded for the HTTP exchange, not protected by that encoding. Use a valid TLS configuration and an HTTPS URL before relying on this method for sensitive content. Redirecting users from HTTP to HTTPS is not a substitute for serving the credential exchange over HTTPS: the authentication request itself must use the encrypted connection.

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

Protect both kinds of access

Transport encryption protects the exchange while it crosses the network; filesystem controls protect the credential file on the server. Limit read and write access to the administrators and Apache process that need it. Do not put the file under a public document root, and do not assume that a hidden filename is a security boundary.

Understand the scope

Basic Authentication identifies a username and verifies a password for each protected request. It does not provide multifactor authentication, account recovery, password rotation, session management, or application-level roles. If the site needs those capabilities, use an authentication system designed for them and treat Apache Basic Authentication as a simple front-door control rather than a full identity platform.

Practical deployment checklist

  • Install apache2-utils with sudo apt update and sudo apt install apache2-utils.
  • Create the credential file once with htpasswd -c; omit -c for subsequent users.
  • Store the file outside the document root and URI space, such as /etc/apache2/.htpasswd.
  • Use an absolute AuthUserFile path.
  • Choose a central <Directory>/virtual-host block or a delegated .htaccess file.
  • If using .htaccess, permit authentication overrides with AllowOverride AuthConfig in the matching directory block.
  • Select Require valid-user for all file users or Require user username for a named account.
  • Run sudo apache2ctl configtest before applying changes.
  • Reload with sudo systemctl reload apache2 and inspect the error log if it fails.
  • Verify a 401 challenge without credentials and a successful response with a valid account.
  • Perform real authentication tests over HTTPS with a valid TLS configuration.
  • Review file ownership and permissions whenever an account is added, removed, or the credential file is moved.

Which configuration approach should you choose?

Use a central <Directory> or virtual-host policy when you administer the Ubuntu server and want one auditable place for access control. It avoids the extra override dependency and makes deployment, syntax testing, and rollback part of the normal Apache configuration workflow.

Use .htaccess when directory-level delegation is a genuine requirement, such as a site owner who cannot edit the virtual-host file. Accept the additional operational responsibility: the file must be in the correct directory, the enclosing block must allow AuthConfig, and mistakes can be difficult to spot if several directories contain similar files. In either approach, the credential file, directives, HTTPS requirement, and testing procedure remain the same.

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.

Final verification before opening the directory to users

Check the complete request path rather than only the configuration text. Confirm that the hostname resolves to the intended Ubuntu server, Apache selects the intended virtual host, the URL maps to the directory named in the policy, and the credential file is readable at the exact path specified. Then test anonymous, invalid, valid, and unauthorized-user cases over HTTPS. This sequence distinguishes a routing error from an authentication error and an authentication success from a filesystem permission failure.

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.