nginx Password-Authentification without apache2-tools

If you have already installed nginx and are thinking about adding a password-protection (like the apache .htaccess).
If you google, you will find a lot of answers using apache2-tools.
I don’t want to install anything more than already is installed, so I found a solution with openssl:

okay, so first create a new filder:

mkdir -p /etc/nginx/passwd/

Then let’s add a username.
I assume we call the user “username”.
We will write this into the file for_webpage in the newly created folder.

You need to be root to do this.

sh -c "echo -n 'username:' >> /etc/nginx/passwd/for_webpage"
sh -c "openssl passwd -apr1 >> /etc/nginx/passwd/for_webpage"

in the second line it will ask you for your password. Just type it in.

if you look into the file it should now look like this:


Now just add it into your webpage-settings from nginx.
find the location / and add it below the try-files like this:

    location / {
        try_files $uri $uri/ =404;
        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/passwd/for_webpage;

reload nginx and open your site.
you will now see the site requestion your credentials.