2

I want to password protect my developer subdomain (dev.example.com), and leave the main domain publicly available.

I want to do this recursively, so that any file or folder on the subdomain will always prompt you for a login.

In the Nginx config file, I've added the following to my dev.example.com server-block (note that I have separate server-blocks for the main and subdomain):

location ^~ / {
    auth_basic "Administrator Login";
    auth_basic_user_file /home/path/to/.htpasswd;
}

From searching around on SF, I was under the impression that the ^~ identifier makes the password protection recursive, but it doesn't.

While dev.example.com specifically prompts me for a login, dev.example.com/folder/ doesn't.

What am I doing wrong?

Trace DeCoy
  • 153
  • 1
  • 6

2 Answers2

2

To protect the entire subdomain, the statements should appear in the existing server block:

server {
    server_name dev.example.com;
    auth_basic "Administrator Login";
    auth_basic_user_file /home/path/to/.htpasswd;
    ...
}
Richard Smith
  • 11,859
  • 2
  • 18
  • 26
  • My apologies, I thought that was understood: Yes, the code snippet above is in my existing dev.example.com server block – Trace DeCoy Jan 12 '17 at 11:28
  • In your question, you show the `auth_basic` statements inside a `location` block - I am saying it should **not** be inside a `location` block. – Richard Smith Jan 12 '17 at 11:38
  • Ahh, didn't catch that. It works! Thanks. So the location block is only necessary if I'm trying to protect a certain folder, and not (in this case) "root"? – Trace DeCoy Jan 12 '17 at 12:38
  • 1
    Best to think of locations as matching URIs rather than folders. See [this link](http://nginx.org/en/docs/http/request_processing.html) to understand `nginx` request processing. – Richard Smith Jan 12 '17 at 15:35
0

This should work. And make sure to restart nginx after completing the edit.

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html/subdomain;
    index index.php index.html index.html
    server_name dev.example.com;;

    location ^~ / {
        auth_basic "Restricted";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }

}
Don Dilanga
  • 232
  • 2
  • 8