Password Protect Files or Directories with .htaccess

In some instances you may find that you need to secure content on your website and require authentication to access this protected content. This can be achieved by using the awesome flexibility of a little bit of code in your .htaccess file. In this article we will cover how to protect both files and directories using your .htaccess file. If you have not created a .htaccess file or you’re not sure how to edit an already existing .htaccess file, please check out our article: Creating and editing an .htaccess file.

 

How to password protect files

Please be aware that you’ll need to have a valid .htpasswd file in place, as this is where the authorized user credentials are stored. Only valid users in the .htpasswd file will be able to access the protected content. If you’re not sure what an .htpasswd file is or how to create one don’t worry we’ve got you covered! Please refer to the following guide which discusses the .htpasswd file: How to create and use .htpasswd.

 

With this example you can see how you can protect a single file using the following code inside of your .htaccess:

 

 

How to password protect multiple files

The second example illustrates how to use the FilesMatch directive to ensure the protection of any file that matches the pattern specified in the rule.

 

#Protect multiple files that match the pattern with a password

 

How to password protect directories

The final example shows you how to password protect a directory that the .htaccess file is in.

 

 

By using any of the examples in this article you should now be able to share content both efficiently and securely with any user that you authorize.


Share:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.