nginx: enable basic authentication

What is Basic Authentication?

Basic authentication is a simple authentication schema build into the HTTP protocol.
The client sends HTTP request with the Authorization header that contains a base-64 encoded string from username:password values

For example: Authorization: Basic YXBpdXNlcjpDSUNhcGkwMQ==

I have assinged this task so want to take a note for enabling basic authen in nginx

How to enable basic authen in nginx

Refer nginx site in here

  • first, install nginx http://nginx.org/en/download.html

  • Generate a Password File
    you can use the htpasswd or apache2-utils (Debian, Ubuntu) or httpd-tools (RHEL/CentOS/Oracle Linux).

    1
    2
    3
    4
    5
    6
    7
    8
    htpasswd -c ./.htpasswd admin
    New password:
    Re-type new password:
    Adding password for user admin

    ---
    cat .htpasswd
    admin:$apr1$MnWfNTQr$AiRKKJd.pfSgIN.fMcanJ/ <== Encrypted password
  • Configuring nginx
    you can limit access to the whole website with basic authentication by specify the auth_basic directive at server

    1
    2
    3
    4
    5
    6
    server {
    ...
    auth_basic "Basic Auth";
    auth_basic_user_file /usr/local/etc/nginx/.htpasswd;
    ...
    }

    test config:

    1
    2
    nginx -t
    nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is ok

    reload nginx:

    1
    2
    nginx -s quit
    nginx
  • Test your setting
    Login request
    Login Success

Refer