Apache: protect the contents of a directory
Today we see a rather simple system for restricting access to a given directory available on an Apache web server so that we are prompted for credentials.
Let's say we have it available on the webserver, in addition to the main site, one or more complementary directories, the content of which must be inhibited to the regular user and made available only to those who hold the credentials.
/ |-> index.html |-> style.css |-> wordpress |-> protected_files
In the example above we have, in addition to files index and style le directory
protected_files. The first will contain all the contents of the site, the second will contain the files that we want to hide from public browsing, protecting them with a password.
To set a password on Apache it will be enough to create the files
.htpasswd within the directory
.htaccess we will insert the following lines:
AuthName "AREA RIVERVATA"
Be careful to specify the correct internal path to the server, not the address reachable from the outside.
.htpasswd it will contain the username and password (of the password, only the hash will be saved). There are several online sites to generate the hash, or the htpasswd command from the apache-utils package (presumably already installed). To generate the content of
.htpasswd run the following command from the terminal:
htpasswd -nbBC 10 pippo pluto
-b treats second argument as password (pluto)
-n show password as stdout response (it does not save it to a file)
-B use hashing function “bcrypt”
-C 10 set bcrypt cost to 10 (technically specifies an iterative count of key expansion in a power of two)
In this example we will create the credentials with user “Foo” e password “pluto“. The output will be the following:
Foo:$2and $ 10 $ Vr456iXtzafSd21bK8ZTguSTLRcaBFoOMUgA1ZwLJRuFQFf.6QQCW
We paste the output as it is in the file
.htpasswd, we upload both files to the directory “protected_files” and reload the page.