The first step is to create a password file which Apache will use to check the username and password. This file will be named .htpasswd and put in a secure location: /etc/apache2 on Ubuntu 16.04, and /etc/httpd on CentOS 7.
The htpasswd command can be used to either create a password file or add an entry to it. For this first time, we will use the -c flag to create the file and add the username jdoe:
- CentOS 7:sudo htpasswd -c /etc/httpd/.htpasswd jdoe
- Ubuntu 16.04:sudo htpasswd -c /etc/apache2/.htpasswd jdoe
You will be prompted to enter and confirm the new password for the user.
Add a New User to an Existing File
To add a new user to an existing password file, use the same command without the -c flag. For example, to add a user janedoe the command is:
- CentOS 7:sudo htpasswd /etc/httpd/.htpasswd janedoe
- Ubuntu 16.04:sudo htpasswd /etc/apache2/.htpasswd janedoe
You will be prompted to enter and confirm the new password for the user.