One of the standard tasks that can be solved by using .htaccess is restricting access to a specific directory on the server. For example, you need to give access to a certain directory to individual visitors, providing them with a unique login and password.
In the directory to which we want to restrict access by password, we create a .htaccess file with the following directives:
AuthType Basic
AuthName "Some Name"
AuthUserFile /home/uXXXXX/.htpasswd
require valid-user
The path /home/uXXXXX/.htpasswd denotes the full path to the password file on our server disk. If, for example, you place the .htpasswd file (it will contain passwords) in your home directory, where you get to by logging into the server via FTP, then the path to this file will look like /home/uXXXXX/.htpasswd, where uXXXXX is the name of your virtual sites (for example, u12345).
In the AuthUserFile directive we specify the absolute path to the file with logins/passwords, which we will create a little later. If you create the .htaccess file on your computer, and not directly on the server using a text editor, please note that .htaccess must be transferred via FTP strictly in text (ASCII) mode.
Create a password file. The password file should contain lines like login:password. The password must be encrypted using the MD5 algorithm. One way to create such a file is to use the program included with Apache – htpasswd (on our server it is located in the /usr/local/bin/ directory, the full path is /usr/local/bin/htpasswd).
Let’s look at how to create a password file in the Unix shell directly on the server. Let’s go to the shell and execute the following commands:
htpasswd -mbc .htpasswd user1 sNQ7j9oR2w
htpasswd .htpasswd user2
Add user2 to the existing .htpasswd file, and enter the password manually in response to the corresponding program request.
If you use Windows and do not want to use the unix shell to generate passwords, you can download the Windows version of the htpasswd program here and create a file with passwords on your computer, then upload it to the server. If you already have a Windows version of Apache installed, the htpasswd.exe file can be found in the Program Files\Apache Group\Apache\bin\ directory.
So, get htpasswd.exe and use it to generate passwords like this:
htpasswd.exe -mc .htpasswd user1
create a new password file htpasswd.exe, the password and its confirmation will be requested interactively
htpasswd.exe -m .htpasswd user2
add the user user2 to the existing password file htpasswd.exe, requesting the password interactively.
After all logins have been created, the file must be uploaded to the server.