.htaccess stands for “hypertext access”. This is the default Apache directory level configuration file. .htaccess can be used to secure a particular directories in web server. One of the most common uses is to require user authentication in order to serve certain web pages.
Create .htaccess File.
First create a .htaccess file in your website document root to protect entire site or in specific directory and add following content.
AuthType Basic AuthName "Secure Content" AuthUserFile /home/myuser/public_html/.htpasswd require valid-user
Create Users in .htpasswd
Now start with creating users in .htpasswd defined in .htaccess file. You can add user and password either in plain text or md5 encrypted.
Adding password in plain text format:
# htpasswd -c /home/myuser/public_html/.htpasswd myuser
Adding password with md5 crypt format
# htpasswd -cm /home/myuser/public_html/.htpasswd myuser
Configure Apache to allow .htaccess Authentication
By default Apache doesn’t allow to use of .htaccess, So you also need to update below setting in your httpd.conf to allow .htaccess based authentication. We use Allowoverride variable to define if .htaccess will read by apache or not.
From: AllowOverride none To: AllowOverride AuthConfig
To set AuthConfig will allow only authentication in .htaccess, rest of setting (if any) will be ignored. To allow all setting defined in .htaccess file use “All” in place of AuthConfig”.
Restart Apache and Test Setup.
After making any changes in apache configuration file (httpd.conf or apache2.conf), you need to restart Apache web service.
For CentOS/RHEL 6/5 Users:
# service httpd restart
For CentOS/RHEL 7 Users:
# systemctl enable httpd.service
For Ubuntu/Debian Users:
# service apache2 restart
Thanks for reading this article, I hope it will help you to understand to set up basic authentication in Apache using .htaccess.