Password Protect a Domain with nginx


2013-09-11

It's very easy to place a simple htpasswd-based authentication system on a domain served by nginx. To do this, you'll want your server block to look like this:

server {
    listen 80;
    server_name domain.com;
    root /site/root;
    index index.html index.htm;
    auth_basic            "Restricted";
    auth_basic_user_file  /etc/nginx/htpasswd;
}

The relevant lines here are the last two defining auth_basic and auth_basic_user_file. Notice that the file is /etc/nginx/htpasswd. This means you need to use htpasswd to create that file:

yourusername@server:~$ sudo htpasswd -c /etc/nginx/htpasswd yourusername
New password: 
Re-type new password: 
Adding password for user yourusername

This will create the password file. Next reload nginx's configuration:

sudo nginx -s reload

Now when you visit your domain, you will be asked to enter a username and password that you chose beforehand. This is definitely not the most secure way of restricting domain access, but it's something. Check out htpasswd's help for more secure options:

htpasswd --help