• Time to read less than 1 minute

Here is a simple way to restrict the public access to a directory and force authentication for the allowed users.

1. Create a .htpasswd file

Run the following command to create a .htpasswd file in the directory that should have a restricted access:

htpasswd -c .htpasswd user1

In this example, we are creating authentication credentials for the user name user1. After running the command, above, you will be asked to type a password for the user name, and confirm the provided passowrd.

After, confirmation, run the ls -a command to view the contents of the current directory and confirm that the .htpasswd file has been created.

Don't forget to set the right permissions for the newly created .htpasswd file:

chmod 644 .htpasswd

2. Create a .htaccess file

In the same directory create a .htaccess file that will reference the .htpassword credentials file, and display an authentication window for any user attempting to access the directory in question. Put the following content in the newly created .htaccess file:

AuthName "Login window title"
AuthType Basic
AuthUserFile /protected/dir/.htpasswd
Require valid-user

After performing these actions, trying to access the protected directory via a browser will display a login prompt for which you can provide the previously defined user credentials.