9

Is it possible to limit authentication in Nginx to a specific username? I.e I have multiple subdomains and want to limit that subdomain to ONLY 1 user. All the users are in 1 .htpassword file. In Apache you can do it as follows:

AuthType Basic
AuthName "Restricted Files"
AuthBasicProvider file
AuthUserFile /usr/local/apache/passwd/passwords
Require user rbowen

However I haven't been able to find a similar way in Nginx.

This is how my current Nginx setup is. I have one of these in each server {} block for each user.

auth_basic "Restricted";
auth_basic_user_file /usr/local/apache/passwd/passwords;
2
  • You could create an HTTP endpoint which validates the user against the path and returns 200 or an error if it's not allowed. You then reference this endpoint with the ngx_http_auth_request module.
    – Marc
    Sep 29, 2022 at 7:46
  • @Marc it's not required, added the answer with the config example
    – Reishin
    May 6, 2023 at 10:27

2 Answers 2

6

If I understand the question well, you have a file containing multiple user names and passwords and you want to limit the authentication to a specific user from that file for each server block and keep the configuration centralized ?

Unfortunately you can't do that with nginx, you will need to split the file into multiple ones containing only one user:password pair.

1

Actually with some trickery it's possible:

    auth_basic "Restricted";
    auth_basic_user_file /usr/local/apache/passwd/passwords;

    set $AUTHFAIL "";
    if ($remote_user != "rbowen") {
      set $AUTHFAIL "1";
    }
    # required, when user is not yet authorized to ... basically authorize 
    if ($remote_user = "") {
      set $AUTHFAIL "";
    }

    if ($AUTHFAIL = "1") {
      return 403;
    }

Here we setting a variable to be empty, if it empty we are good to go. But if authorized user not matching the pattern - the further request would fail with HTTP 403.

Also, by changing the pattern, it is possible to provide a list of the users or move the construction to the location block and use different users for each location block

2
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    May 17, 2023 at 10:31
  • @bot dear bot, this is authored response and not copied from another site to be cited here
    – Reishin
    May 19, 2023 at 11:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .