Centos 7 – Password Protect a Directory with Apache Password htpasswd

Last updated on August 11th, 2019 at 01:35 pm

Create User for apache basic authentication

htpasswd -c /etc/httpd/.htpasswd your_user

You will prompt for User password

If you want another user run this from additional user:

htpasswd /etc/httpd/.htpasswd user2

This how httpaswd save passwords in .htpasswd

Change password to user

htpasswd -b /etc/httpd/.htpasswd <username> <password>

 

Open the main Apache configuration file for editing with the command:
sudo nano /etc/httpd/conf/httpd.conf
Scroll down to the <Directory> section for "/var/www/html" and change AllowOverride to All.

Save and exit the file. Then restart Apache for the changes to take effect:
sudo systemctl restart httpd

Create the Restricted Area

Go to the directory you want to protect. For example:

cd /var/www/html/admin

Create a file called .htaccess and open it for editing:

sudo nano .htaccess

Put the following into this file:

CentOS 7:

AuthType Basic
AuthName "Password Required"
Require valid-user
AuthUserFile /etc/httpd/.htpasswd

OR

Put following in to binding of your website /etc/httpd/httpd.conf between <Directory "/var/www/postfixadmin" & </Directory>;

 

<VirtualHost 192.168.33.22:443>
SSLEngine On
SSLCertificateFile /var/www/ssl/mail.domain.com.crt
SSLCertificateKeyFile /var/www/ssl/mail.domain.com.key
DocumentRoot "/var/www/postfixadmin"
ServerName postfixadmin.domain.com
<Directory "/var/www/postfixadmin">
AuthType Basic
AuthName "Password Required"
Require valid-user
AuthUserFile /etc/httpd/.htpasswd
</Directory>
	 <Location /var/www/web-interface>
  AuthUserFile /etc/httpd/.htpasswd
  AuthName "Password Protected Area"
  AuthType Basic
  Require valid-user
</Location>
</VirtualHost>