Access restriction using .htaccess

Sometimes a convenient method to restrict access to certain sections of a website (such as the administrator panel or confidential data) is to use access restriction with .htaccess (or, alternatively, basic authentication). Of course, with scripts, this can be done more elegantly, conveniently, and sometimes even more securely. The thing is, all the information needed to gain access is sent with each request in the form of headers. But if this is not critical, then it can be used; it is probably the fastest option.

.htaccess allows for setting directory access restrictions.

To gain access, the user will be prompted to enter a password.

To do this, create a file named .htaccess in the protected directory with the following contents:

AuthName "Protected part"
AuthType Basic
AuthUserFile /path/.htpasswd
require valid-user
When attempting to access, the user will see the message "Protected part" and will be asked to enter a password. Note the location of the password file: you need to provide the address relative to the server's root directory.

If you want to restrict access only to a specific file:

<Files protected.zip>
AuthName "Protected file"
AuthType Basic
AuthUserFile /path/.htpasswd
</Files>
Regular expressions are supported in the file name, so you can restrict access to a group of files:
<Files ".(rar)$">
AuthName "Protected part"
AuthType Basic
AuthUserFile /path/.htpasswd
</Files>
Generating the .htpasswd file in GNU/Linux:
htpasswd -cm .htpasswd admin
The -c flag means creating the file, -m - MD5 password encryption. admin is the username. You will then be prompted to enter and confirm the password. That's it. Now we have learned how to protect directories and individual files using .htaccess.