====== Apache - Authentication - Basic Authentication ====== To restrict access to certain HTTP resources, create two files: .htaccess and .htpasswd (or equivalent per httpd.conf setting). ---- ===== Configure Apache to allow .htaccess authentication. ===== By default Apache does not allow the use of .htaccess files. * Apache will need to be configured to allow **.htaccess** based authentication. Editing the Apache config file: sudo vi /etc/httpd/conf/httpd.conf Find the section that begins with ****. Change the line from **AllowOverride none** to **AllowOverride AuthConfig**. AllowOverride AuthConfig Save and close the file. ---- ===== 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. * A hidden file **.htpasswd** will need to be created in the /etc/httpd/ configuration directory. For example, create a .htpasswd file for user1. sudo htpasswd -c /etc/httpd/.htpasswd user1 This will prompt to supply and confirm a password for user1. **WARNING**: Only use **-c** the first time the file is created. * Do not use **-c** when another user is added in the future. ---- Create another user named user2: sudo htpasswd /etc/httpd/.htpasswd user2 ---- ===== Display the username and encrypted password for each user ===== sudo cat /etc/httpd/.htpasswd returns: user1:$apr1$0r/2zNGG$jopiWY3DEJd2FvZxTnugJ/ user2:$apr1$07FYIyjx$7Zy1qcBd.B8cKqu0wN/MH1 ---- ===== Allow Apache to read the .htpasswd file ===== sudo chown apache:apache /etc/httpd/.htpasswd sudo chmod 0660 /etc/httpd/.htpasswd ---- ===== Configure Apache password authentication ===== Create a **.htaccess** file in the web directory which is to be restricted. For example, create the .htaccess file in the /var/www/html/ directory to restrict the entire document root. sudo vi /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. sudo apachectl restart ---- ===== Testing password authentication ===== Try to access the restricted content in a web browser by visiting the URL or static IP address. This will prompt for a username and password to access the website. **NOTE:** If the correct credentials are entered, the site will be accessible. * If the wrong credentials or entered, or **Cancel** is pressed, this should show the **Unauthorized** error page. * Password protection should be combined with SSL, so that the credentials are not sent to the server in plain text. ---- ===== References ===== http://www.webtrafficexchange.com/how-create-htpasswd-file-encrypted-password