How to Configure Basic Authentication in NGINX

configure basic authentication in nginx

NGINX allows you to set up basic authentication, just like Apache, thereby allowing access to only authorized users. Here’s how to configure basic authentication in NGINX.


How to Configure Basic Authentication in NGINX

Here are the steps to configure basic authentication in NGINX. We will use Apache’s htpasswd tool to create a list of authorized users (with passwords) and point NGINX config file to use it.


1. Install htpasswd

Open terminal or SSH into your Linux system and run the following command

Using Apt-Get:

$ sudo apt-get install apache2-utils

Using Yum:

$ yum install httpd-tools


2. Create User Credentials File

Create a hidden file .htpasswd in /etc/nginx/ folder. You can name this file anything you want. Just make it hidden by adding a dot (.) in front of it.

Let’s create the file with user1 in it

$ sudo htpasswd -c /etc/nginx/.htpasswd user1

You will be asked to provide a password and confirm it.

Use ‘-c’ flag only the first time while creating the file. To add more users (e.g user2) don’t use it.

$ sudo htpasswd /etc/nginx/.htpasswd user2


After you have added all the required users, you can view the file

$ sudo cat /etc/nginx/.htpasswd

You’ll see a list of usernames and encrypted passwords



If you want to use md5 encryption use -m option with htpasswd command


3. Edit NGINX configuration

Open NGINX config in a text editor

$ sudo vim /etc/nginx/nginx.conf


Add the following lines (in bold) to the server context to add site-wide authorization requirement

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


If you only want authorization for specific URLs or directories (e.g /restricted/), add the above 2 lines in a location context

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



4. Reload NGINX Server

Reload NGINX Server to apply changes

$ sudo /etc/init.d/nginx reload


That’s it! Now NGINX will allow only the users mentioned in your .htpasswd file to access your web pages.

Open a web browser and try accessing a web page on your site.

Every time a visitor tries accessing a protected web page, they will be asked to provide username & password.

configure basic authentication nginx


If they enter the correct credentials, they will be sent to the desired URL, else they will see a “403:Access forbidden” message.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!