Date Posted:06-01-2017

In many scenario, we don’t want particular page to be crawled by bots or we want page to be restricted for particular users. In this post, we gonna explain on how to add authorization page on nginx webserver. Incase, if the server doesn’t have nginx installed, please follow the post on install nginx on Ubuntu

Assumption:
  1. Ubuntu
  2. Webserver – Nginx
  3. Installation Directory – /etc/nginx
Implementation:

Let’s assume that we want the folder “web” to be protected by password and there is only one domain exist on the server and configuration file is /etc/nginx/sites-enabled/default. Incase if you want to enable password protection for domain specific then we need to edit appropriate domain configuration file.

Open default configuration file using your favorite editor and append the following line under server { blocks.

vi /etc/nginx/sites-enabled/default

location /web/ {
auth_basic “Restricted Content”;
auth_basic_user_file /var/www/html/web/.htpasswd;
}

In our example, we have used the location /var/www/html/web/.htpasswd file to store the password. We can use different location if we don’t want file to be kept outside of documentroot.

Now, let’s create a password a passwd file. We can use online tools to create htpasswd content or alternatively we can use htpasswd command line to create the password file.

htpasswd -c /var/www/html/.htpasswd username


New password:
Re-type new password:
Adding password for user username


Incase if htpasswd command doesn’t exist, install apache2-utils(apt-get install apache2-utils)

Check for any syntax error on nginx configuration

nginx -t


nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful


Restart nginx service to get the changes get into effect.

systemctl restart nginx

Access the page on the browser http://IPADDRESS/web.  The page will be prompted for authorization page.

 

Leave a Reply