How to Create HTTP Basic Authentication With .Htpasswd and .Htaccess in Apache

HTTP Basic Authentication is a simple yet effective way to secure web pages or directories on your Apache web server. It requires users to enter a username and password to access protected content. In this guide, we’ll walk you through the steps to set up HTTP Basic Authentication using .htpasswd and .htaccess files on an Apache web server.

Prerequisites

Before you begin, ensure you have the following:

  • A server running Apache.
  • SSH or terminal access to your server.
  • Basic knowledge of working with the command line.

Step 1: Create the .htpasswd File

The .htpasswd file contains the usernames and their corresponding hashed passwords. You’ll use the htpasswd command to create this file. Replace “admin” with the username you want to create.

1
htpasswd -c /var/www/html/.htpasswd admin

You will be prompted to enter and confirm the password for the user.

Step 2: Create the .htaccess File

The .htaccess file is used to configure directory-specific settings, including authentication. Create or edit the .htaccess file in the directory you want to protect. You can use a text editor like Vim or Nano to do this.

1
vim /var/www/html/.htaccess

Add the following lines to your .htaccess file:

1
2
3
4
AuthType Basic
AuthName "Unauthorize"
AuthUserFile /var/www/html/.htpasswd
Require valid-user

Save and exit the text editor.

Step 3: Restart Apache

To apply the changes, you need to restart the Apache web server. The command to do this varies depending on your server’s operating system.

On Ubuntu/Debian:

1
sudo systemctl restart apache2

On CentOS/RHEL:

1
sudo systemctl restart httpd

Step 4: Test Authentication

Visit the directory or webpage you’ve protected in your web browser. You should be prompted to enter a username and password. Enter the credentials you set in the .htpasswd file, and you should gain access to the protected content.

Congratulations! You have successfully set up HTTP Basic Authentication using .htpasswd and .htaccess on your Apache web server. This simple yet effective method can help secure specific areas of your website that require restricted access.

Remember to keep your .htpasswd file secure, as it contains sensitive information. Additionally, consider using HTTPS to encrypt the data transmitted during authentication for an added layer of security.

That’s it! Your content is now protected by HTTP Basic Authentication.

0%