Backend Development

FrontEnd Development

How to restrict access to a web application with Basic Auth in Nginx

Sep 7, 2024

  • 2 mins read

Learn how to restrict access to your web application by setting up basic authentication in Nginx.

Guest Author
Guest Author

Contributor

How to restrict access to a web application with Basic Auth in Nginx

Restricting access to your web application using basic authentication in Nginx is an effective way to secure your resources. This comprehensive guide provides step-by-step instructions on how to implement basic auth by installing the htpasswd utility, generating a password file, and configuring Nginx to authenticate users. After testing the configuration, you will learn how to restrict access to specific areas of your website, define realms for authentication, and reload Nginx. This guide is particularly useful for administrators looking to add a layer of security without the need for complex authentication mechanisms.

1. Install htpasswd utility

The htpasswd command is part of the Apache HTTP server utilities, which you may need to install if it's not already available.

  • On Debian/Ubuntu:
sudo apt-get install apache2-utils 

  • On CentOS/RHEL:
sudo yum install httpd-tools

2. Create the password file

Use the htpasswd command to create a file that will store the username and password for authentication.

sudo htpasswd -c /etc/nginx/.htpasswd 
  • Replace <username> with your desired username.
  • You will be prompted to set a password.

If you want to add more users, run:

sudo htpasswd /etc/nginx/.htpasswd 

3. Configure Nginx to use basic authentication

Edit your Nginx configuration file to protect a specific location with basic authentication.

Example configuration:

server {
    listen 80;
    server_name example.com;

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

        # Other configurations (proxy, root, etc.)
    }
}
  • auth_basic "Restricted Area"; defines the realm (a message shown to the user in the browser).
  • auth_basic_user_file /etc/nginx/.htpasswd; tells Nginx where the password file is located. 

4. Test and reload Nginx

Test your Nginx configuration for syntax errors:

sudo nginx -t

If everything is fine, reload Nginx:

sudo systemctl reload nginx
 

Now, when users access the protected location (e.g., your website), they will be prompted for the username and password.

logo

Dhrubok Infotech Services Ltd. (DISL) is one of the top full-service software development companies in Dhaka, Bangladesh that delivers up-to-the-minute iOS, Android Apps and Enterprise Web Solutions. We exist to help startups and enterprises of all sizes to build better products, reach more people and have a prominent online presence.

Follow Us

© 2024 Dhrubok Infotech Services ltd.

Terms of Use & Privacy Policy