All posts
Published in Latest Articles

Restricting Access with HTTP Basic Authentication in NGNIX

Profile image of Atakan Demircioğlu
By Atakan Demircioğlu
Fullstack Developer
To add password protection to a website hosted by NGINX, you can use the built-in HTTP Basic Authentication feature. This will require…
Restricting Access with HTTP Basic Authentication in NGNIX image 1

Restricting Access with HTTP Basic Authentication in NGNIX

To add password protection to a website hosted by NGINX, you can use the built-in HTTP Basic Authentication feature. This will require visitors to enter a username and password before accessing the website.

Table Of Contents;

· Generate an Encrypted Password
· Update NGINX Configuration
· Restart NGINX


Generate an Encrypted Password

You need to generate an encrypted password to use in the NGINX configuration. You can use the htpasswd command-line tool for this.

If it's not already installed, you can install it using the package manager on your system.

For example, to generate an encrypted password for the username “admin”, you can run the following command:

htpasswd -c /etc/nginx/.htpasswd admin

You’ll be prompted to enter a password for the user “admin”, and the encrypted password will be stored in the specified file (/etc/nginx/.htpasswd in this example).

Update NGINX Configuration

You need to update your NGINX configuration file to enable password protection for the desired location or website.

Open the NGINX configuration file using a text editor. The file is usually located at /etc/nginx/nginx.conf, /etc/nginx/conf.d/default.conf, or in a custom configuration file for your website.

Within the server block or the location block for the specific URL you want to protect, add the following lines:

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

Make sure to adjust the path /admn/ to match the URL or path you want to protect, and update the path /etc/nginx/.htpasswd to match the path where you stored the encrypted password file.

Restart NGINX

Save the changes to the NGINX configuration file and restart the NGINX service to apply the new configuration. The command to restart NGINX depends on your operating system and how NGINX is installed.

For example, on Ubuntu, you can use the following command

sudo service nginx restart

On CentOS or Fedora, you can use:

sudo systemctl restart nginx

After restarting NGINX, access to the specified URL will require visitors to enter the username and password you configured.

Note: Make sure to secure the .htpasswd file by setting appropriate permissions so that it is not accessible to unauthorized users.

Twitter: https://twitter.com/atakde

Github: https://github.com/atakde

If you like to get more updates from me, 
please follow me on Medium and subscribe to email alert.