The .htaccess file is a configuration file used by Apache-based web servers. Directives in .htaccess files can be used to redirect requests to various URLs, control directory listings, create custom error documents, and more. This post will show you how to use a code snippet in .htaccess to secure directories and subdirectories.

If there are any misconfigured rules or erroneous syntax in an .htaccess file, users will get a "Internal Server Error" notice when they visit a page in the same directory. When making changes to an .htaccess file, exercise extreme caution.

Code to protect directories and subdirectories

You can protect files , directories and subdirectories to prevent unauthorized access. Following are the parameters used in the code to protect the folders.

  • AuthType Basic :  The web server's authentication method
  • AuthName “Dialog Prompt”: Popup box title of the username/password.
  • AuthUserFile ../../.htpasswd: This directive instructs the web server where to look for the username/password file. Replace../../.htpasswd with the relative path to your.htpasswd file.
  • Require valid-user: Indicates to the web server which users in the your.htpasswd file have access to your folder; when valid-user is used, the folder is viewable to all users in the file.
Protect the main web directory

To protect the main web directory , add the following code to the .htaccess file:

#Protect Directory

AuthName "Dialog prompt"

AuthType Basic

AuthUserFile /home/username/example.com/.htpasswd

Require valid-user
Protect a web subdirectory

To protect a subdirectory add the following code to the .htaccess file. The  example shows you how to protect the subdirectory named members folder. 

 #Protect Directory

AuthName "Dialog prompt"

AuthType Basic

AuthUserFile /home/username/example.com/members/.htpasswd

Require valid-user
Protect a WordPress subdirectory

When a user tries to access a password-protected folder, Wordpress throws a 404 Not Found. To avoid this, add the ErrorDocument 401 default line, which will result in a “401 Unauthorized” response for site visitors.

ErrorDocument 401 default

 #Protect Directory

AuthName "Dialog prompt"

AuthType Basic

AuthUserFile /home/username/example.com/members/.htpasswd

Require valid-user
Was this answer helpful? 0 Users Found This Useful (0 Votes) htaccess file, htaccess rule, htaccess file protection