How To Setup Basic Authentication on Nginx

Nginx is high performance and lightweight web server. It also work as web reverse proxy and email (POP3/IMAP) proxy server. It runs on Linux, UNIX, BSD, Mac OS X, Solaris and Microsoft Windows. As per the Netcraft more than 6% of all domains on the internet use Nginx web server. Nginx powers several high traffic web sites like WordPress, Github, Hulu, and SourceForge. The need for serving large number of concurrent requests is raising every day. Also Nginx solved the C10K ( i.e 10,000 concurrent clients) Problem.

In this article I will show how to setup basic authentication on Nginx for your website.

In this tutorial I am going to use htpasswd command utility from Apache tools package to generate encrypted credential file.

1. Apache Tools Installation

To create .htpasswd in encrypted login details you will need htpasswd command. So installed following Apache tools to get htpasswd command on your Linux system.

On Ubuntu/Debian System:

$ sudo apt-get install apache2-utils

On CentOS/RHEL Fedora System

# yum install httpd-tools

2. Create Credentials file

First of all you will need to create an empty .htpasswd file if it does not exists. If you use -c option with htpasswd command this will overwrite existing file and you may accidentaly overwrite existing file during adding more users.

# htpasswd -m /etc/nginx/.htpasswd sagar
# htpasswd -m /etc/nginx/.htpasswd santosh

In the above command you can see -m that is used to a create password in md5 encryption.

3. Edit Nginx Configuration File

Now edit your Nginx configuration file for your server block and add the following entry into the server block you need to authenticate.

server {
    listen       80 default_server;
    server_name  _;
    root         /usr/share/nginx/html;
    location / {
	auth_basic "Restricted Area";
	auth_basic_user_file /etc/nginx/.htpasswd;

You can also restrict specific application URL of your websites like below example:

location /Secure/ {
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/nginx/.htpasswd;

4. Restart And Reload Nginx Server

Now relaod the Nginx server using following commands to apply the changes on the server.

# systemctl reload nginx.service


Thank you! for visiting LookLinux.

If you find this tutorial helpful please share with your friends to keep it alive. For more helpful topic browse my website To become an author at LookLinux Submit Article. Stay connected to Facebook.

About the author


Santosh Prasad

Hi! I'm Santosh and I'm here to post some cool article for you. If you have any query and suggestion please comment in comment section.

Leave a Comment