Using HTTP Basic Auth per domain in nginx

Theory

I had to setup multiple web services on single server with nginx as reverse-proxy. Some of them were administration tools like phpMyAdmin, so we needed some sort of authentication. Nginx (the free version) supports HTTP Basic Authentication, which is basically a file with logins and hashed passwords (see /etc/shadow for example). Htpasswd file is generated by "htpasswd" tool in apache2-utils package under Ubuntu, but You could use any htpasswd generator online. Next, I had problems with nginx throwing "open() failed: Permission denied". This was fixed by moving file into /etc/nginx/htpasswd and setting rw-rw-rw- permissions.

How

# Make directory for websites htpasswd file
mkdir /etc/nginx/htpasswd/
    
# Generate new password file (supports multiple users)
htpasswd -c /etc/nginx/htpasswd/your.site.org admin
-password_here-
htpasswd -c /etc/nginx/htpasswd/your.site.org seconduser
-password_here-

# For other domain, create new file
htpasswd -c /etc/nginx/htpasswd/different.site.org user
-password_here-

# Configure Your website nginx configuration file
vim /etc/nginx/conf.d/your.site.org.conf

> In server block add these lines
auth_basic "Text in auth window";
auth_basic_user_file /etc/nginx/htpasswd/your.site.org;
:wq

# Specify permissions
chmod a+rw /etc/nginx/htpasswd/your.site.org;