Search code examples
authenticationnginx.htpasswd

Nginx basic HTML authentication on a subfolder


I need help applying basic HTML authentication to password protect a subfolder on my site - hosted by Digitalocean served using Nginx. I followed the tutorial - https://www.digitalocean.com/community/tutorials/how-to-set-up-http-authentication-with-nginx-on-ubuntu-12-10.

But my results are: 1. The entire site prompts for credentials rather than the specified subfolder, and 2. All the pages on the site can longer find css and js files.

Here's what I tried: 1) Generated a .htpasswd file in the subfolder, 2) Added a location block in the nginx.conf file (see below), and 3) Reloaded nginx.

location / {
auth_basic "Restricted";
auth_basic_user_file /var/www/pepperslice/current/public/ps/jeffaltman/.htpasswd;
}

The complete nginx.config file is as follows:

upstream unicorn {
  server unix:/tmp/unicorn.pepperslice.sock fail_timeout=0;
}

server {
  listen 80 default;
  root /var/www/pepperslice/current/public;
  try_files $uri/index.html $uri @unicorn;

  location = /images {
    root /var/www/pepperslice/current/public/images;
  }

  location @unicorn {
    proxy_pass http://unicorn;
  }

location / {
auth_basic "Restricted";
auth_basic_user_file /var/www/pepperslice/current/public/ps/jeffaltman/.htpasswd;
}

  error_page 500 502 503 504 /500.html;
}

At the moment, the location block I added is commented out.

I am seeking help on how I can: 1. password protect the subfolder pepperslice.com/ps/jeffaltman, and 2. password protect other subfolders using different username and password combinations.

Also, any ideas why the css and js paths failed? I am guessing once the authentication problem is fixed, the css/js path problem will go away.

Thanks.


Solution

  • After some more research I found a solution and solved the issue. This guide is where I found it - see section 3 - https://www.howtoforge.com/basic-http-authentication-with-nginx

    Instead of the location block starting with "location / {...}" (root for site), for a subfolder it should start with the subfolder path. For example:

    location /ps/jeffaltman {
    auth_basic "Restricted";
    auth_basic_user_file /var/www/pepperslice/current/public/ps/jeffaltman/.htpasswd;
    }
    

    Also the css and js path problem disappeared.

    Cheers.