Nginx basic auth

From wikinotes

Enables HTTP BASIC AUTH using an htpasswd file.

Documentation

official docs https://nginx.org/en/docs/http/ngx_http_auth_basic_module.html

Tutorials

digitalocean https://www.digitalocean.com/community/tutorials/how-to-set-up-password-authentication-with-nginx-on-ubuntu-14-04

Basic Auth

Use an htpasswd file to determine allowed logins/credentials.

http {
  server {
    location / {
      auth_basic "requires authentication";
      auth_basic_user_file /usr/local/www/mywebsite/htpasswd;
    }
  }
}

Basic Auth with Cookies

http {
  map $cookie_myauth $auth_basic_enabled {
    "1234567abcdefg" "yes";  # cookie value
    default           "no";
  }
  
  server {
    listen 80;
    server_name mysite.example.org;

    location / {
      auth_basic  $mysite_authentication;
      auth_basic_user_file  htpasswd/mysite;
      add_header Set-Cookie "myauth=1234567abcdefg;max-age=3153600000;path=/";
    }
  }
}

Basic Auth with Cookies and pre-approved Address Ranges

map $cookie_letmein $mysite_hascookie {
  "someRandomValue" "yes";
  default           "no";
}

geo $mysite_geo {
  192.168.0.0/24 "yes": #some network which should have access
  10.10.10.0/24  "yes": #some other network which should have access
  default        "no";
}


map $mysite_hascookie$mysite_geo $mysite_authentication{
  "yesyes" "off";  #both cookie and IP are correct  => OK
  "yesno"  "off"; #cookie is ok, but IP not  => OK
  "noyes"  "off";  #cookie is not ok, but IP is ok => OK
  default  "Your credentials please"; #everythingles => NOT OK
}

server {
  listen 80;
  server_name mysite.example.org;
  location / {
    auth_basic  $mysite_authentication;
    auth_basic_user_file  htpasswd/mysite;
    add_header Set-Cookie "letmein=someRandomValue;max-age=3153600000;path=/"; #set that special cookie, when everything is ok
    proxy_pass http://127.0.0.1:8000/;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $remote_addr;
  }
}

Copied from https://www.liip.ch/en/blog/no-nginx-basic-auth-with-either-network-or-cookie-set through stack overflow