When you want to secure specific URL or route, you can configure Basic auth using Nginx.
First install apache2-utils
as apt dependency.
sudo apt install apache2-utils
You can add usernames to .htpasswd
by running the following command. The username we’ve chosen is alice
, of course, change this to fit your requirements.
sudo bash -c "echo -n 'alice:' >> /etc/nginx/.htpasswd"
Next, we’ll need to add a hashed password to the user we just created by running the following command. You will be prompted for a password, and you will be asked to verify that password once again.
sudo bash -c "openssl passwd -apr1 >> /etc/nginx/.htpasswd" --> Password:
Verifying - Password:
Before restricting anything, you need to decide what you would like to restrict. Nginx is very flexible here and allows you to restrict access to the entire server (therefore, your configuration should reside in the configuration’s server block) or, to a specific location (therefore, your configuration should reside in the configuration’s location
block).
We shall be restricting a directory named private that resides in the root of the server. We want the rest of the server to function normally and be accessible to all users.
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name localhost;
location / {
try_files $uri $uri/ =404;
}
location /private {
try_files $uri $uri/ =404;
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
}
sudo service nginx restart
You can open the URL and alert will popup to input username and password.