sudo sh -c "echo -n 'username:' >> /etc/nginx/.htpasswd"
You can type any name in place of username.
sudo sh -c "openssl passwd -apr1 >> /etc/nginx/.htpasswd"
This command will ask you what password you want and encrypt it.
cat /etc/nginx/.htpasswd
Edit your desired server block. In this case, we are adding password authentication on default block
sudo vim /etc/nginx/sites-enabled/default
If you don't add this line under location / {} it may loop the user authentication.
auth_basic "Login";
auth_basic_user_file /etc/nginx/.htpasswd;
sudo nginx -s reload