Using HTTP Basic Auth per domain in nginx


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.


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

# For other domain, create new file
htpasswd -c /etc/nginx/htpasswd/ user

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

> In server block add these lines
auth_basic "Text in auth window";
auth_basic_user_file /etc/nginx/htpasswd/;

# Specify permissions
chmod a+rw /etc/nginx/htpasswd/;