.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
  • AuthType: defines the type of authentication. Basic means there is no encryption and the password hash is sent as clear text.
  • AuthName: is content which displayed on web page when prompts for user name and password.
  • AuthUserFile: is file which stored user credentials.
  • require valid-user: indicates that only successful authenticated requests may load of the page.
  • 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
  • -c : is used only for first time when you create .htpasswd file. If you use it second time, it will remove existing file and recreate new one.
  • -m : is used to save password in md5 format.
  • 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.

    AllowOverride none
    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.