How To Set Up HTTP Authentication With Nginx On Ubuntu 14.04

Step 1: Install Apache Utils

To generate encrypted password for the nginx we need to use apache2-utils, use this command :

sudo apt-get install apache2-utils

Step 2: Create username & password

create a .htpasswd under the folder we need to protect or under your website root directory :

sudo htpasswd -c /var/www/ test-admin

Later it will prompt you for a password

New password:
Re-type new password:
Adding password for user test-<span class="highlight">admin</span>

This htpasswd file must be own by current web user

Step 3: Update your Nginx configuration

Under /etc/nginx/sites-available/ add this line:

location /admin {
auth_basic "Restricted";
auth_basic_user_file/var/www/<span class="highlight"><span class="highlight">;

Step 4: Test and reload Nginx

Test the new configuration first for any error and later reload Nginx:

sudo nginx -t
sudo nginx -s reload