Petros Kyriakoupersonal blog

I am a full stack web developer. Love tinkering all the time, especially anything javascript related.

How to password protect your staging server using NGINX

January 15, 2020

cover image

How to password protect your staging server using NGINX

As part of preparing a staging server for my startup, I was looking into ways I could secure it so that its only accessible to specified users.

Below I will show how you can easily secure your staging server at the NGINX server and only people with correct credentials will be able to access.

The Idea

The basic idea is given below in the sample nginx configuration file. The example is for a single-page application like React which always needs to redirects to / for the react router to kick in but the two lines of interest are auth_basic and auth_basic_user_file.

# example.conf

server {
    listen 80;
    server_name <server-name>;

    location / {
        root   /usr/share/nginx/html;
        index  index.html;
        try_files $uri $uri/ /index.html;
        auth_basic "Restricted Access";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
}

auth_basic directive

As part of NGINX comes a module called auth_basic which defines an area (or the whole) of NGINX as password-protected. By supplying the following two lines:

auth_basic "Restricted Access";
auth_basic_user_file /etc/passwords/htpasswd;

You are telling NGINX to secure everything under / path with a 'Restricted Access' message and a path to the hashed username/passwords of allowed users.

In turn NGINX on accessing / on the server, it will prompt the user for a username and password to login. If the username/password combination is correct the user will be given temporary access (few days) to the server until NGINX requires a re-login.

Creating users

Before being able to create users you need to define a file that will be accessible by NGINX. By convention the file is usually called .htpasswd or htpasswd - being synonymous with the actual tool that creates the users called htpasswd.

The htpasswd tool is part of appache2-utils and can be installed using the following:

sudo apt install apache2-utils

After thats done, you can create users using the following command, which will prompt for a password and saved in the .htpasswd file.

sudo htpasswd -c <path-to-htpasswd-file> <username>

Example

Creating a user1 goes like this:

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

If you now check the .htpasswd file you will see the following:

cat /etc/nginx/.htpasswd
user1:$apr1$/woC1jnP$KAh0SsVn5qeSMjTtn0E9Q0

What can be observed is that the password is hashed to avoid storing plain passwords and its evaluate (as a hash) when the user enters the password during authentication.

Restart NGINX

sudo service nginx restart

Conclusion

As we can see its quite simple to password-protect parts of your app. For more information you can refer to the official documentation.