How to Password Protect One File in Apache


password protect one file apache

Apache allows you to password protect files, directories and even your entire website. In this example, we look at how to password protect one file in Apache.

 

How to Password Protect One File in Apache

Here are the steps to password protect one file in Apache. Before we proceed, please ensure that you have enabled mod_rewrite (.htaccess file) on your Apache server. Here are the steps to do it:

  1. Ubuntu/Debian systems
  2. CentOS and similar systems

 

1. Create password file

First, we create a password file that will store a list of usernames and encrypted passwords of authorized users. You can do that with htpasswd tool.

Create a hidden file .htpasswd in /etc/ folder. Make it hidden by adding a dot (.) at the beginning of its filename.

Next, let’s add the first user (e.g user1) to it.


$ sudo htpasswd -c /etc/httpd/.htpasswd user1

In the above command, use the ‘-c’ flag only the first time you add a user. You will be asked to enter a password that user and confirm it.

Let us add one more user to the file


$ sudo htpasswd /etc/httpd/.htpasswd user2

 

After you have added all the required users, you can view the file


$ sudo cat /etc/httpd/.htpasswd

You’ll see a list of usernames and encrypted passwords


user1:$sahubekjeiuehfjkeEJenj3nrkrnugJ/
user2:$jk234bh3rbjhrbB8k3b3hb3bMH1

 

Change the ownership and permissions of the file to ensure that only Apache can access it.

$ sudo chown apache:apache /etc/httpd/.htpasswd
$ sudo chmod 0660 /etc/httpd/.htpasswd

 

3. Set up Password Authentication in Apache

Next, create a .htaccess file in your website’s root directory, if not present already.


$ sudo nano /var/www/html/.htaccess

 

Add the following lines to it. Let us say if you want to protect only the file result.php, then add the following lines to .htaccess file. Replace “result.php” with the file you want to protect.


<FilesMatch "result.php">
AuthName "Member Only"
AuthType Basic
AuthUserFile /etc/.htpasswd
require valid-user
</FilesMatch>

Please remember to put the full absolute path of .htpasswd file’s directory (e.g /home/username/public_html/.htpasswd)

 

Save & Close the file. Restart Apache to apply changes


$ sudo apachectl restart

 

4. Test Password Authentication

Open a web browser, and visit the URL you just protected (e.g http://www.example.com/result.php). You will see an authentication form asking for username and password.

If you enter the right user credentials, you will see the requested web page. If you provide wrong info or hit cancel, you will see an error message.

 

That’s it! You know how to password protect one file in Apache.

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!