Securing nginx folders

December 22, 2012

I wanted to have a folder on my nginx webserver that prompts for a username/password before showing any html pages inside that folder.

Here's the existing location declaration in the nginx config:

location / {
  root            /home/drumcoder/web/drumcoder.co.uk;
  index           index.html;
}

Here's the new declaration that includes the secure folder

location ^~ /secure/folder/ {
  root                    /home/drumcoder/web/drumcoder.co.uk;
   index                  index.html;
  auth_basic              "Restricted Area";
  auth_basic_user_file    file.htpasswd;
}

The secure folder is accessed at http://drumcoder.co.uk/secure/folder - note that this offset isn't included in the root directive, but the files for it are still located within, e.g. /home/drumcoder/web/drumcoder.co.uk/secure/folder/index.html

The file.htpasswd file is a normal apache .htpasswd file with the following format:

username:password
username2:password2

Use the tool at http://www.tools.dynamicdrive.com/password/ to create passwords for this file.

References

Tags: nginx