Published April 12, 2018 by

Set Up Password Authentication in Apache on CentOS/RedHat

In this tutorial, we will learn how to password-protect website or content on an Apache web server running on CentOS and RedHat based server.

Allow .htaccess Authentication

By default, Apache does not allow the use of .htaccess files. We will need to set up Apache to allow .htaccess based authentication.

We can do this by editing the Apache configuration file (httpd.conf).

# sudo vim /etc/httpd/conf/httpd.conf

In httpd.conf file, find the section that begins with <Directory "/var/www/html">. Change the line from AllowOverride none to AllowOverride AuthConfig

AllowOverride AuthConfig

Save and close the file.

Create Password File

We can use htpasswd to create a password file that Apache can use to authenticate users. We will create a hidden file for this purpose called .htpasswd within our /etc/httpd/ configuration directory.

The first time we use this utility, we need to add the -c option to create the specified file. We specify a username (subhash) at the end of the command to create a new entry within the file.

# sudo htpasswd -c /etc/httpd/.htpasswd Subhash

Here it will be asked to password for the user.

Only use -c the first time you create the file. Do not use -c when you add a user in the future.

# sudo htpasswd  /etc/httpd/.htpasswd Adam

If you want to view the contents of the file, you can see the username and the encrypted password for each record

# cat /etc/httpd/.htpasswd

Configuring Apache Password Authentication

Now we need to create a .htaccess file in the web directory we wish to restrict. In this example, we will create the .htaccess file in the /var/www/html/ directory to restrict the entire document root.

# sudo vim /var/www/html/.htaccess

Add below code to a .htaccess file.

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

Save and close the file.

Restart Apache

# sudo apachectl restart

Time to Test

After everything has been set up, it's time to test your Apache server. Try to access your website in a web browser. You should be presented with a username and password prompt that looks like this.

If you enter the correct credentials, you will be allowed to access the website. If you enter the wrong credentials or hit "Cancel", you will see the "Unauthorized" error page.