How to protect a website folders using .htaccess

The.htaccess file is a configuration file that Apache-based web servers use. In .htaccess files, you can use directives to redirect requests to different URLs, control directory listings, specify custom error documents, and more. This article will show you how to protect directories, subdirectores using a code snippet in .htaccess.To learn more about how to use .htaccess files, click on this link

If there are any misconfigured rules or incorrect syntax in an .htaccess file, users see an “Internal Server Error” message when they visit a page in the same directory. Be very careful when you make any changes to an .htaccess file.

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 .thaccess 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

More Information

To view an online tutorial for using .htaccess files, please visit http://httpd.apache.org/docs/2.2/howto/htaccess.html.

Did you find this article helpful? Then you'll love our support. Experience the A2 Hosting difference today and get a pre-secured, pre-optimized website. Check out our web hosting plans today.

We use cookies to personalize the website for you and to analyze the use of our website. You consent to this by clicking on "I consent" or by continuing your use of this website. Further information about cookies can be found in our Privacy Policy.