skip to Main Content

In my nginx configuration I have turned on basic auth to restrict access to the site like this:

auth_basic "Restricted Area";
auth_basic_user_file /path/to/htpasswd;

This works for users, but some tools we are using doesn’t support basic auth so we need to use a query parameter instead of basic auth for these.

auth_basic can’t be placed in an if-block so nginx won’t accept this configuration:

if ($arg_auth_token = "my secret value") {
    auth_basic "Restricted Area";
    auth_basic_user_file /path/to/htpasswd;
}

How can I solve this?

2

Answers


  1. Chosen as BEST ANSWER

    The solution is rather similar to the naive approach: use a variable and set it in the if-block instead.

    set $auth "Restricted Area"; # Default to basic auth enabled
    
    # Check the value of the auth_token query parameter
    if ($arg_auth_token = "my secret value") {
        set $auth off; # Disable basic auth
    }
    
    auth_basic $auth; # This is now conditional based on the value of $arg_auth_token
    auth_basic_user_file /path/to/htpasswd;
    

  2. The same can be achieved using the map block (which is better than using if in the location context):

    map $arg_auth_token $realm {
        "my secret value"  off;
        default            "Restricted Area";
    }
    server {
        ...
        auth_basic $realm;
        auth_basic_user_file /path/to/htpasswd;
    

    Caution! This trick cannot be used with any nginx directive, even if it accept the variables for its parameter. For example, trying to use this with the access_log directive won’t give you some kind of conditional logging – it will create the log file named off instead.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search