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 DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
VGSOURCES
Get listed

access controlPATCH 2026.10.15

How to Restrict Directories in Nginx While Keeping File Access

By VGSources Team 10 min read

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.

Separate the directory URI from the file URIs. Require authentication on the slash-terminated directory endpoint, keep autoindex disabled, and use a more-specific file location only when those known files are meant to be public. If authentication is inherited, auth_basic off; in that file location removes it. Test index redirects, trailing-slash variants, and nested paths separately because Nginx can select a different location after an internal redirect.

The basic configuration pattern

This example protects /downloads/ while allowing direct requests for files below it. The document root is /srv/www, so /downloads/manual.pdf maps to /srv/www/downloads/manual.pdf.

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.
server {
    root /srv/www;

    # Canonicalize the URI without a trailing slash.
    location = /downloads {
        return 301 /downloads/;
    }

    # Directory endpoint: credentials are required.
    location = /downloads/ {
        auth_basic 'Restricted directory';
        auth_basic_user_file /etc/nginx/.htpasswd;
        autoindex off;
        try_files $uri $uri/ =404;
    }

    # Known files: public only if that is your intentional policy.
    location ^~ /downloads/ {
        auth_basic off;
        try_files $uri =404;
    }
}

The exact-match location (= /downloads/) wins over the longer prefix when the request is exactly the directory URI. A request for /downloads/manual.pdf instead uses the ^~ /downloads/ prefix and is served without the inherited Basic Authentication challenge. The try_files check prevents a missing path from being passed to an unrelated fallback or application handler.

This is a policy example, not a universal drop-in. If every file must be private, do not switch authentication off in the broader file location. If only a small allowlist of files is public, create exact public locations for those files and leave the general directory location protected.

#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

What each directive controls

Basic Authentication

The ngx_http_auth_basic_module limits access by validating a username and password using HTTP Basic Authentication. auth_basic may be set in the http, server, location, or limit_except context. The password file named by auth_basic_user_file must be readable by the Nginx worker process.

Authentication is inherited from broader configuration blocks. Therefore, a server-level or parent-location challenge can still apply to a file location unless that location explicitly contains auth_basic off;. Conversely, adding auth_basic off; is a security decision: it makes every file matched by that location public unless another access control blocks it.

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

Directory listings

The autoindex module processes requests ending in a slash and generates a listing only when autoindex on; is enabled. Its default is off. You do not need to enable autoindex to serve a known file, so keeping it off hides generated listings while preserving direct file requests.

Filesystem checks

try_files checks candidate paths using the active root or alias. When it finds a match, Nginx serves it or internally redirects as appropriate; when no candidate exists, the final parameter supplies the result. Use try_files $uri =404; for a file-only location and try_files $uri $uri/ =404; when the directory endpoint must recognize an existing directory.

Decide the access policy before writing locations

Policy Directory URI Known files Recommended shape
Private directory and private files Authenticated Authenticated One protected prefix; do not use auth_basic off.
Protected directory endpoint, public direct files Authenticated Public Exact slash location plus a public file prefix, as in the main example.
Protected directory with a small public allowlist Authenticated Only named files public Exact public file locations and a protected catch-all prefix.
Network-restricted area Allowlisted addresses, credentials, or both The same or a different rule Combine allow, deny, Basic Auth, and satisfy deliberately.

“Restrict the directory” can mean hiding the listing, challenging visitors, allowing only selected networks, or all three. Nginx cannot infer which interpretation you intend. Write the policy for the directory URI, files, index document, nested directories, and errors before choosing a location hierarchy.

Variants for common policies

Protect every file

Use a protected prefix when credentials should be required for both the directory endpoint and every descendant file. The exact no-slash location simply provides a predictable canonical URI.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter | USB C Dongle with 90W Max Power Delivery, 3×5Gbps USB A Data Ports, for MacBook, Dell, and More (Charger Not Included)
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
server {
    root /srv/www;

    location = /downloads {
        return 301 /downloads/;
    }

    location ^~ /downloads/ {
        auth_basic 'Private downloads';
        auth_basic_user_file /etc/nginx/.htpasswd;
        autoindex off;
        try_files $uri $uri/ =404;
    }
}

Because there is no public child location, an internal redirect to an index file remains inside the protected prefix. This is usually the least surprising configuration for genuinely private material.

Expose only named public files

If most content is private, avoid a broad public prefix. Define exact locations for the files that are deliberately public, then protect the remaining subtree.

server {
    root /srv/www;

    location = /downloads {
        return 301 /downloads/;
    }

    location = /downloads/readme.pdf {
        auth_basic off;
        try_files $uri =404;
    }

    location = /downloads/manual.zip {
        auth_basic off;
        try_files $uri =404;
    }

    location ^~ /downloads/ {
        auth_basic 'Private downloads';
        auth_basic_user_file /etc/nginx/.htpasswd;
        autoindex off;
        try_files $uri $uri/ =404;
    }
}

Exact locations are easier to audit than a rule that makes every future file public. Each newly added file remains protected until you intentionally add another exact exception.

Combine IP rules and passwords

allow and deny are useful when access should be limited to a corporate network, VPN range, or maintenance address. They are inherited only when the current level defines neither directive. The satisfy directive determines how IP checks interact with other access modules.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
location = /downloads/ {
    allow 192.0.2.0/24;
    deny all;

    auth_basic 'Restricted directory';
    auth_basic_user_file /etc/nginx/.htpasswd;
    satisfy all;
    autoindex off;
    try_files $uri $uri/ =404;
}

With satisfy all, a client must pass both the address rule and Basic Authentication. With satisfy any, one successful access check is sufficient; that can allow an approved network to bypass the password, so document that result explicitly. Apply the same controls to the file locations if files must follow the same network policy.

Implement the configuration safely

  1. Choose the URI contract. Decide whether /downloads redirects to /downloads/, returns an error, or is handled elsewhere. Handle both forms explicitly rather than relying on behavior from another location.
  2. Confirm the filesystem mapping. With root /srv/www;, verify that the intended file really exists below /srv/www/downloads/. If you use alias, calculate the replacement path carefully because alias maps the matching location to a different filesystem path rather than appending the complete URI.
  3. Create and protect the password file. Put the file outside the publicly served tree, set ownership and permissions so the Nginx worker can read it, and ensure ordinary HTTP requests cannot reach it. A worker that cannot read the file cannot complete authentication.
  4. Set the directory location. Put the challenge, password-file path, autoindex off;, and the appropriate try_files behavior on the slash-terminated URI.
  5. Add public exceptions only when required. Use auth_basic off; only in locations whose complete contents are intended to be public. For a small allowlist, prefer exact file locations to a broad public prefix.
  6. Define the index policy. Decide whether an index document should be served after authentication, served publicly, or blocked. Add an exact location for the index file when it must have a different rule from other files.
  7. Protect sensitive names. Add explicit denies for password files, private keys, deployment manifests, source archives, and other operational material. Exact locations are valuable when a broad ^~ prefix would otherwise prevent a later regular-expression location from being considered.
  8. Validate syntax before reloading. Run nginx -t. Reload through the service manager used by the host only after the test succeeds, and keep the previous configuration available for a quick rollback.

Location matching and internal redirects

Why the slash matters

/downloads/ and /downloads are different URI strings. An exact location for the slash form does not automatically define the no-slash form. A canonical redirect keeps links consistent, but it does not itself decide whether the destination requires credentials. Test the redirect and the destination as separate requests.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Why a file can escape the directory rule

Nginx first selects a location for the requested URI. A more-specific exact location takes precedence; otherwise prefix and regular-expression rules are considered according to Nginx’s matching algorithm. In the main pattern, the exact directory location handles only one URI, while the ^~ prefix handles descendants. That deliberate split is what permits direct-file access.

Index processing is a second decision

The index module processes slash-ended requests. If an index file is found, Nginx can internally redirect to that file URI, which may be selected by a different location. Consequently, a protected /downloads/ endpoint can end up serving /downloads/index.html under the public file rule unless you account for it.

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

To keep the index protected while leaving other files public, add a more-specific protected location:

location = /downloads/index.html {
    auth_basic 'Restricted index';
    auth_basic_user_file /etc/nginx/.htpasswd;
    try_files $uri =404;
}

location = /downloads/ {
    auth_basic 'Restricted directory';
    auth_basic_user_file /etc/nginx/.htpasswd;
    autoindex off;
    try_files $uri $uri/ =404;
}

location ^~ /downloads/ {
    auth_basic off;
    try_files $uri =404;
}

If the directory must never disclose an index, do not rely on a public descendant rule. Keep the entire subtree protected, or configure an explicit response for the directory URI and verify the resulting behavior.

root, alias, and try_files pitfalls

Using root

With root /srv/www;, Nginx appends the request URI to the root. A request for /downloads/a.zip therefore checks /srv/www/downloads/a.zip. This is straightforward when the URL hierarchy mirrors the disk hierarchy.

Using alias

alias replaces the location portion with another path. It is useful when /downloads/ should map to a directory such as /data/releases/, but a missing or extra trailing slash can map requests unexpectedly. Test both a file and a directory with the exact location syntax you deploy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray | Data transfer & Fast charging for MacBook, iPhone 17/16/15, iPad, Samsung Galaxy, Apple Watch
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
location ^~ /downloads/ {
    alias /data/releases/;
    auth_basic off;
    try_files $uri =404;
}

When an alias mapping behaves unexpectedly, inspect the final filesystem path and simplify the location before adding more directives. Do not assume that changing root to alias leaves try_files semantics unchanged.

Do not use a permissive fallback accidentally

A fallback such as try_files $uri /index.php?$args; may send a missing download path to an application. For a static file area, finish with =404 unless an application fallback is an explicit requirement.

Hardening the directory

  • Leave autoindex off; unless a generated listing is an intentional feature.
  • Keep .htpasswd, private keys, environment files, deployment manifests, source archives, and backup files outside the document root whenever possible.
  • Add exact deny locations for sensitive files that must remain under the served tree. Exact matches take precedence over a general descendant prefix.
  • Review permissions on both the content directory and the password file. Nginx needs read and directory-traversal permission, while other users should not receive unnecessary access.
  • Decide how to handle nested directories. A public prefix can expose files in every nested path, while a file-only try_files $uri =404; rule will not create a browsable listing.
  • Include percent-encoded names, dot segments, repeated slashes, and unexpected extensions in your security review. Normalize or reject paths according to the policy of the application and filesystem.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Verification checklist

These checks are validation steps to run on your host; they are not a substitute for reviewing the complete server configuration.

Request Expected observation in the public-file pattern What a failure suggests
/downloads Canonical redirect to the slash form, if configured The no-slash location is missing or another server block is handling it.
/downloads/ Authentication challenge; no generated listing Wrong location, inherited access rule, or an unexpected index.
/downloads/known.pdf File response without a Basic Auth challenge auth_basic off; is not in the selected location, or another access module applies.
/downloads/missing.pdf 404 A permissive fallback or application route is catching missing files.
/downloads/index.html The status required by your index policy An internal redirect is selecting the public file location.
Nested directory URI No accidental listing; status matches your policy The broad prefix exposes more than intended.
Unauthorized IP Denied according to allow/deny and satisfy Rules were inherited, overridden, or combined differently than expected.

Use a header-only client such as curl -I for status and redirect checks, and a normal request when you need to confirm the response body. Inspect whether a 401 response includes WWW-Authenticate. Test authenticated and unauthenticated requests separately, and test the exact host name and port that users will access.

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

Troubleshooting

The directory is protected, but files also return 401

Check which location matched the file URI. A server-level or parent-location auth_basic may still be inherited, or the request may be handled by a protected regex location. Put auth_basic off; only in the intended public file location and verify that no IP rule or application middleware is still denying access.

index.html is public when it should be private

The slash request was probably internally redirected to the file location. Add an exact protected location for the index file, or use one protected prefix for the entire directory. Then test both the slash URI and the index URI directly.

Best Value
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Known files return 404

Verify the physical path produced by root or alias, capitalization, permissions, and the final try_files argument. With an alias, recheck trailing slashes and the relationship between the location prefix and replacement directory.

A listing appears unexpectedly

Find the location that handled the slash-ended request and check for autoindex on; at that level or above. Remember that a different nested location may have its own setting. Turn it off explicitly in the directory policy and remove any unintended index or fallback behavior.

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

Authentication fails even with correct credentials

Confirm that the worker can read /etc/nginx/.htpasswd, that the file format is valid, and that the request reaches the server block containing the expected password-file path. Check the Nginx error log after running nginx -t and before reloading again.

Changes do not take effect

Run nginx -t against the configuration actually loaded by the service, reload through the host’s service manager, and verify the active worker processes. A request may also be reaching a different server block because of the Host header, port, or TLS listener.

Choosing the safest final layout

Use a single protected prefix when the directory and all descendants are private. Use the exact-slash-plus-public-prefix pattern only when every file matched by that prefix is intentionally public. For mixed content, exact public file locations provide the clearest review boundary. In every layout, define the no-slash URI, index behavior, nested paths, missing-file response, and sensitive filenames explicitly, then validate the actual status codes and authentication headers after each configuration change.

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.

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

access controlBasic AuthenticationNGINXServer Configurationweb server

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
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

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.