Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk8 min

How to Password-Protect a Folder With NGINX Basic Auth

A practical NGINX guide to protecting one folder with Basic Authentication, including htpasswd setup, location blocks, permissions, HTTPS, public exceptions, testing, and troubleshooting.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To password-protect one folder, add auth_basic and auth_basic_user_file to the matching NGINX location block. Create the credentials file with Apache’s htpasswd utility, keep that file outside the public document root, make sure the NGINX worker can read it, then test and reload the configuration. Basic Authentication is only base64-encoded, not encrypted, so serve the protected URL over HTTPS.

What NGINX Basic Authentication protects

NGINX Basic Authentication guards a URL path, not a physical directory by itself. NGINX first matches the requested URL against a location block. The directives in that block then require a username and password before NGINX serves the matching files or proxies the request.

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.

The two directives have separate jobs:

  • auth_basic enables the HTTP Basic Authentication challenge and sets the realm text shown by the browser’s login prompt.
  • auth_basic_user_file points to a flat file containing accepted usernames and password hashes.

A typical arrangement protects /private/ while leaving the rest of the virtual host public. The URL prefix and the filesystem path do not have to share the same name, but the root or alias mapping must point the location at the intended files.

Prerequisites and planning

  • Administrative access to the server so you can install a package, create a credentials file, edit NGINX configuration, and reload the service.
  • A working NGINX server block for the hostname you will protect.
  • An HTTPS listener and certificate for any account that will send real credentials.
  • The exact URL prefix to protect, such as /private/, and the filesystem directory that should serve it.
  • A location for the password file that is readable by NGINX but is not downloadable through the public site.

Installation layouts differ by distribution and by whether NGINX came from the operating-system packages, a vendor repository, a container image, or a managed service. Treat /etc/nginx/.htpasswd and the examples below as adaptable paths rather than universal defaults.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Install the htpasswd utility

The htpasswd command is supplied by different packages depending on the operating system.

Operating-system family Package providing htpasswd Example installation command
Debian or Ubuntu apache2-utils sudo apt install apache2-utils
RHEL, CentOS, or Oracle Linux httpd-tools sudo dnf install httpd-tools

Use the package manager and package name appropriate to your release. Installing this utility does not require replacing NGINX with Apache; the command simply creates a password file that NGINX understands.

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

Create the password file

Create the first account

Choose a protected, absolute path and create the file with the -c option:

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

Enter the password when prompted. The utility writes the username and a password hash to the flat file. Use -c only for the initial file creation.

Add another account

When the file already exists, omit -c:

sudo htpasswd /etc/nginx/.htpasswd bob

This updates the existing file with another username. Repeat the same form for each additional account. Do not use the create-file option as a routine way to add users.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Choose a safe location and permissions

Place the file outside the public document root whenever possible. A path such as /etc/nginx/.htpasswd cannot normally be requested as a web document, whereas a file under /var/www/html could become downloadable if a location rule or static-file mapping exposes it.

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

NGINX worker processes open the password file for every authentication check. The worker account therefore needs read access to the file and traverse access to each parent directory. At the same time, avoid making the file broadly readable. The exact owner, group, and mode depend on your distribution and NGINX service account; identify that account in your installation and grant only the read permission it needs.

If the worker cannot open the file, authenticated requests fail even when the username and password are correct. Check both the file’s mode and the permissions on every directory in its path.

Protect one folder with a location block

Put the authentication directives inside the location that serves the private URL. This example maps /private/ to the private directory beneath /var/www/html:

server {
    listen 443 ssl;
    server_name example.com;

    location /private/ {
        root /var/www/html;
        auth_basic 'Private files';
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
}

With this mapping, a request such as https://example.com/private/report.pdf is looked up beneath /var/www/html/private/. Replace the hostname, listener details, document root, URL prefix, and password-file path with the values used by your server.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

The realm in auth_basic is the descriptive label a client may display in its credential prompt. It is not a username, password, or access-control rule. The file named by auth_basic_user_file is an absolute filesystem path, not a URL.

Check that the URL really selects this location

NGINX chooses locations according to its location-matching rules. Make sure the requested path begins with the prefix you protected and that another, more specific location is not serving the same files without the authentication directives. A configuration protecting /private/ does not automatically protect similarly named paths such as /privates/ or a separate URL mapped to the same directory.

Protect an entire server and make one path public

You can apply Basic Authentication at the server level when most of a virtual host should be private:

server {
    listen 443 ssl;
    server_name example.com;

    auth_basic 'Private site';
    auth_basic_user_file /etc/nginx/.htpasswd;

    location /public/ {
        auth_basic off;
    }
}

Authentication settings are inherited by nested contexts. auth_basic off cancels an inherited setting for the public location, so requests under /public/ do not receive the login challenge while other locations in the server remain protected.

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

If only one folder needs protection, placing the directives directly in that folder’s location is usually easier to audit. Server-level protection is useful when private access is the default and there are only a few deliberately public exceptions.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Test and reload NGINX safely

  1. Save the edited configuration using the path and include structure used by your installation.
  2. Run the configuration test:
    sudo nginx -t
  3. Continue only when the test reports a successful configuration. Syntax errors, misspelled directives, and unreadable included files must be corrected first.
  4. Reload NGINX without stopping active workers:
    sudo systemctl reload nginx
  5. Open the protected URL in a private browser window or another client. It should request credentials. Correct credentials should allow the resource to load; missing or incorrect credentials produce an HTTP 401 Authorization Required response.

Service-manager commands vary with the installation method. On a containerized or managed deployment, use that environment’s reload mechanism after running the equivalent configuration check.

Test from the command line

A client that supports Basic Authentication can make the result explicit:

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

The command prompts for Alice’s password rather than putting it in shell history. Inspect the HTTP status and response headers. A successful response confirms that the URL matched the protected location, the worker could read the file, and the credentials matched an entry.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use HTTPS: Basic Auth is not encryption

HTTP Basic Authentication transmits the username and password in a base64-encoded authorization value. Base64 is an encoding format, not confidentiality. Without TLS, someone able to observe the connection can recover the credentials and reuse them.

Terminate HTTPS on the NGINX server or on a trusted proxy in front of it, and redirect or otherwise prevent clear-text HTTP access to the protected path. The login prompt alone does not make an HTTP connection secure. Also avoid embedding passwords in URLs, screenshots, tickets, or shell commands that record process arguments.

Password-file formats and account maintenance

NGINX’s Basic Authentication module accepts password entries using traditional crypt, Apache’s apr1, and RFC 2307 forms. The module documentation warns against unsalted SHA-1 entries identified by {SHA} for new passwords. Let htpasswd generate and update entries instead of manually converting hashes.

Adding and removing people

Add a person with htpasswd as shown above. To remove an account, use the utility’s delete operation supported by your installed version, then test the resulting file and reload NGINX if the file change is not being picked up immediately. Keep a controlled record of who should have access, because every username in the file can authenticate to every location that references it.

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

Changing a password

Run htpasswd for the existing username without -c, enter the new password, and verify access with a fresh client session. Existing browser sessions may cache credentials, so test in a private window or clear the client’s stored authentication state.

When a flat file is no longer enough

A single .htpasswd file is straightforward for a small number of users and a few protected paths. Larger teams may need centralized identity, group membership, audit trails, single sign-on, or automated deprovisioning. Those requirements call for an external identity or access-control system rather than expanding one shared flat file indefinitely. The NGINX directives shown here remain appropriate when a local file is the intended control.

Troubleshoot common failures

Observed result Likely cause What to check
The browser never prompts The request is not reaching the protected location. Confirm the URL prefix, active server block, and any more-specific location that may be handling the request.
Every login attempt returns 401 The credentials do not match the file, or NGINX cannot read the file. Re-enter the username and password, verify the absolute path, and check worker read and parent-directory permissions.
Requests fail immediately after the edit A configuration syntax error or invalid include prevents a clean reload. Run sudo nginx -t, fix the reported file and line, then reload only after the test succeeds.
A supposedly public path still asks for credentials It inherited authentication from a higher-level context. Put auth_basic off; in that nested public location and reload the tested configuration.
The password file can be fetched as a web page The file is inside an exposed document root or another location maps it publicly. Move it outside the document root, review static-file mappings, and test the URL directly to ensure it is not downloadable.

Look at the NGINX error log as well as the HTTP response when diagnosing file-access problems. A valid username and password cannot succeed if the worker process is denied access to the credential file.

Choose the right scope and operating model

Decision Option Effect
Protection scope One location Only the selected URL path requires Basic Authentication; the rest of the server can remain public.
Protection scope Server-level directives Authentication is the default for the virtual host, with selected locations able to disable inheritance.
Credential storage Flat htpasswd file Simple local administration with usernames and hashes in one file readable by NGINX.
Credential storage External identity system More operational complexity, but a better fit for centralized accounts, groups, auditing, or single sign-on.
Transport HTTPS/TLS Encrypts the connection that carries the Basic Authentication header.
Transport Plain HTTP Does not provide confidentiality for the base64-encoded credentials and should not be used for real passwords.

Deployment checklist

  • Install the package that supplies htpasswd for your operating system.
  • Create the initial file with -c; omit that option when adding users.
  • Store the file outside the public document root and restrict its filesystem permissions.
  • Verify that the NGINX worker account can read the file and traverse its parent directories.
  • Place auth_basic and auth_basic_user_file in the exact location that serves the private URL, or deliberately inherit them from the server context.
  • Use auth_basic off for any nested path that must remain public.
  • Run sudo nginx -t before every reload.
  • Reload NGINX, then test both an unauthenticated request and a valid authenticated request.
  • Use HTTPS/TLS for every connection that carries these credentials.
  • Review usernames and remove accounts that no longer need access.

Once those checks pass, NGINX is enforcing the password challenge at the URL boundary, while the password file remains a server-side credential store rather than a public web asset.

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

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
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver 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.