Protecting Folders with .htpasswd/.htaccess

From Brian Nelson Ramblings
Jump to: navigation, search

Protecting Folders with .htpasswd/.htaccess

When setting up a web server, there are often sections of the site that you wish to restrict access to. Web applications often provide their own authentication and authorization methods, but the web server itself can be used to restrict access if these are inadequate or unavailable.

Install the Apache Utilities Package

You'll need the htpassword command to configure the password that will restrict access to the target website. This command is part of the httpd-tools package, so the first step is to install that package.

yum install -y httpd-tools

Create a password file with htpasswd

The htpasswd command is used to create and update the files used to store usernames and password for basic authentication of Apache users. We will create a hidden file .htpasswd in the /etc/httpd/ configuration directory.

Let's begin by creating a .htpasswd file for user1.

htpasswd -c /etc/httpd/.htpasswd user1

You will be asked to supply and confirm a password for user1.

Note: Only use -c the first time you create the file. Do not use -c when you add a user in the future. Let's create another user named user2:

htpasswd  /etc/httpd/.htpasswd user2

After creating user2, you can see the username and the encrypted password for each record:

cat /etc/httpd/.htpasswd

The output will look something like this:

user1:$apr1$0r/2zNGG$jopiWY3DEJd2FvZxTnugJ/
user2:$apr1$07FYIyjx$7Zy1qcBd.B8cKqu0wN/MH1

Now, you need to allow the apache user to read the .htpasswd file.

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

Configure Apache password authentication

Now you need to create a .htaccess file in the web directory you wish to restrict.

For this example, we will create the .htaccess file in the /var/www/html/ directory to restrict the entire document root.

vim /var/www/html/.htaccess

Add the following content:

AuthType Basic
AuthName "Restricted Content"
AuthUserFile /etc/httpd/.htpasswd
Require valid-user

Save and close the file, then restart Apache to make these changes take effect.

service httpd restart

or

httpd -k restart

Conclusion

Your website is now secure with password authentication. Remember that password protection should be combined with SSL, so that your credentials are not sent to the server in plain text.