Nginx: Implementing basic authentication
Here we are going to implement this basic authentication, which pops up as guard when someone visits your secret site or admin panel or whatever.
Please note that it a basic authentication, just a simple extra layer to security. I use this to protect my login page.
So, if you cancel this basic authentication you will end up with this beautiful 401 Authorization Required default page. Ofc, you can reload to try again
How to set up this authentication
Before I begin here are is the environment am using —
- Ubuntu 20.04
- Nginx/1.18.0 (Ubuntu)
Let’s start with an example:
- Am going to protect access to my domain — http://your-target-domain.com
- With username: salmon
and password: bluewhale
Let’s begin the steps—
- First, we will use Ubuntu’s preinstalled Perl package to get our encrypted password string. The syntax is
perl -le 'print crypt("your-password", "salt")';
. In our case, it will be :
$→perl -le 'print crypt("bluewhale", "bit2salty")'
- Once executed you will get something like
sov2fNiy1PMc
, basically our encrypted “bluewhale”, we will need it soon. - Now lets
cd /etc/nginx
, here we will create a file.htpasswd
which will contain our username and password.
$ →sudo vim .htpasswd
- Here we will put our username and the Perl generated encrypted password string (in step 2), separated with a semicolon. Like this: (no space between)
$ →salmon:sov2fNiy1PMc
then save the file by — pressing “Esc” and type:wq
→ Press “Enter”.
Note: You can add as many “user:password” entries as you like, by adding each combination in a new line, just one below another. - Next, we have to open our Nginx server block
for “your-target-domain.com” and add the following 2 lines —
auth_basic "Administrator Login";
auth_basic_user_file /etc/nginx/.htpasswd;
- The server block should look something like this —
server {
listen 80; server_name your-target-domain.com; auth_basic "Administrator Login";
auth_basic_user_file /etc/nginx/.htpasswd; location / {
...
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
- Check if everything is all right :
$ →sudo nginx -t
- Lastly, reload Nginx for the changes to take effect
$ →sudo systemctl reload nginx
Now visit your target domain and am sure it will work, as I while am writing this while practically doing it on my AWS ec2 instance.
Thanks