Security and SSL

Exclude a directory or file when protecting a directory with a username and password

Reviewed on 3 min read access passwords .htaccess

cPanel has a Directory Privacy option that lets you protect a directory with a username and password.

This feature is useful for anything from protecting access to a website under development to, in the case of WordPress, adding an extra layer of protection to the wp-admin directory.

Sometimes, however, you may need to exclude a file or directory from this protection. Following the wp-admin example, some plugins and themes make calls to admin-ajax.php, and if you protect access to wp-admin those calls can fail with an additional authentication prompt.

To do this, you can add a rule to .htaccess that excludes only the exact file that must be public. On Apache 2.4, use the modern Require syntax and place the exception in the protected directory's .htaccess, after checking that the endpoint applies its own authorisation and validation:

<Files "admin-ajax.php">
    Require all granted
</Files>

In this example, only the exact file admin-ajax.php is excluded from basic authentication. The exception does not remove the need for WordPress to validate nonces, permissions and the session for each sensitive action.

Do not replace the file name with a broad pattern or exclude entire administrative directories such as wp-admin: you would remove that layer of protection from all their current and future endpoints. If another resource needs public access, create a separate exception for its exact name, test only that URL and confirm that the rest of the directory still asks for authentication.

Test the exception without opening up the rest

Save a copy of .htaccess outside the public directory before editing it. Respect the application's rules and check whether there are already other Require, Files or FilesMatch blocks that might combine with or override it.

From an unauthenticated session, test the excepted URL and another URL in the same directory that should remain protected. A public response from the endpoint does not mean its sensitive actions should run without the application's authorisation.

If a 500 error appears, restore the previous version and check the error log. If you need to open up an entire subdirectory, first identify its files and access points: the single-file example should not be broadened by swapping it for a general wildcard.

You may also find useful

Something wrong or out of date? Tell us and we will review it.