How to Set Up HTTP Authentication With Nginx On Ubuntu 12.10



Nginx is a free and open-source, high performance web server software popular for its stability, simplicity in configuration and low resource consumption. Being a popular web server, many high traffic sites have been hosted using it. When compared to Apache, its considered to be more resource friendly.

In this tutorial, you will learn how to set up http authentication with Nginx on Ubuntu 12.10.



This tutorial will require you to do the set up of your VPS with Ubuntu. Also you will have to install Nginx on it. If you need more information, check the tutorial on installing nginx.

Now that we have all the required initial set up, let’s start with the set up of http authentication.

Apache Utils


In order to have a user and a password for basic authentication, we will first install Apache2-utils with the command:

sudo apt-get install apache2-utils

The htpasswd will be used to create and generate an encrypted key for the user.

Creating a User and a Password


Before creating the user and password, we will have to create a file .htpasswd within the website directory served by nginx. Run the following command to create the file and add the user and password:

sudo htpasswd -c/var/www/ exampleuser

You will be asked to type in your password:

New password:
Re-type new password:
Adding password for userexampleuser

The htpasswd file structure will look like this:



Nginx Configuration Changes


The nginx configuration file for your website will be under /etc/nginx/sites-available/. Add the following lines of code below the domain path you wish to secure:

auth_basic "Restricted";

For example, let’s assume that the nginx configuration file is /etc/nginx/sites-available/yourwebsite_nginx.conf. It should look like this:

sudo vi /etc/nginx/sites-available/yourwebsite_nginx.conf


server {
  listen       portnumber;
  server_name  ip_address;
  location / {
      root  /var/www/;
      index  index.html index.htm;
      auth_basic "Restricted";
     #For Basic Auth
  #For Basic Auth


Reload Nginx


Once you are done with all the changes, you should reload the nginx and try to access the domain that has been secured just now:

$ sudo /etc/init.d/nginx reload
* Reloading nginx configuration...

Now, try accessing the website or domain path and you will be prompted to enter your login and password. Login using the credentials created using htpasswd.

You have successfully secured website path using nginx http authentication.


support2 has written 111 articles

Leave a Reply