Nginx is one of the popular web server used for web hosting. In this tutorial, you will learn to how to configure basic authentication on Nginx for your website. This tutorial will use htpasswd
command utility from Apache tools package to generate encrypted credentials file.
1. Install Apache Tools
You need htpasswd
command to create .htpasswd with encrypted login details. So install apache tools to get the htpasswd
command on your system.
Using Apt-Get:
$ sudo apt-get install apache2-utils
Using Yum:
$ yum install httpd-tools
2. Create Credentials File
First you need to create an empty /etc/nginx/.htpasswd
file if not exists. You can also do this using -c in htpasswd command. But this overwrites existing file and you may accidentaly overwrite existing file while adding more users.
$ touch /etc/nginx/.htpasswd
Above command will create new file or just change timestamp for existing file. Let’s start adding new users using htpasswd command.
$ htpasswd -m /etc/nginx/.htpasswd user1 $ htpasswd -m /etc/nginx/.htpasswd user2
- -m is used for creating md5 encrypted passwords.
3. Edit Nginx Configuration
At this step, edit Nginx configuration file for your server block. Add following entry in 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; } }
Update the location path to restrict specific application url of your web application.
location /restricted/ { auth_basic "Restricted Area"; auth_basic_user_file /etc/nginx/.htpasswd; }
4. Reload Nginx Server
To apply the changes to your server configuration reload Nginx server using the following commands.
$ sudo /etc/init.d/nginx reload
systemctl users can also use the below command.
$ sudo systemctl reload nginx.service
Leave a Reply