How can you set up HTTP basic authentication in Nginx? nginx

How can you set up HTTP basic authentication in Nginx?


Nov. 13, 2023

How to Set Up HTTP Basic Authentication in Nginx

Nginx is a popular web server software that can be configured to authenticate user access using the HTTP Basic Authentication method. This simple authentication mechanism prompts users to enter a username and password before granting access to protected resources.

Step 1: Install Nginx

If you haven't already, you'll need to install Nginx on your server. You can do this by following the installation instructions provided by the Nginx documentation for your specific operating system.

Step 2: Create a Password File

To set up HTTP Basic Authentication, you need to create a password file that contains the usernames and passwords of authorized users. You can create this file using the htpasswd utility, which is included with most web server software.

Open a terminal or command prompt and navigate to the directory where you want to store the password file. Then, run the following command to create the file and add a user:

htpasswd -c /path/to/password/file username

Replace /path/to/password/file with the actual path to your password file, and username with the desired username for the user. You'll be prompted to enter a password for the user.

If you want to add more users to the password file, you can omit the -c flag in the above command.

Step 3: Configure Nginx

Open your Nginx configuration file using a text editor. The location of this file may vary depending on your operating system, but it is commonly found at /etc/nginx/nginx.conf or /etc/nginx/conf.d/default.conf.

Add the following lines inside the server block:

  location / {
    auth_basic "Restricted Access";
    auth_basic_user_file /path/to/password/file;
  }
  

Replace /path/to/password/file with the actual path to your password file. These directives enable HTTP Basic Authentication for the specified location and reference the password file containing the authorized usernames and passwords.

Step 4: Test and Reload Nginx

Save the configuration file and exit the text editor. To ensure that your configuration is correct, you can run the following command:

nginx -t

If there are no syntax errors, you can reload Nginx to apply the new configuration:

nginx -s reload

Now, when you access your Nginx server, you should be prompted to enter a username and password before being granted access to the protected resource. Enter the credentials of an authorized user as specified in the password file created in step 2.

Conclusion

By following the steps outlined in this article, you can easily set up HTTP Basic Authentication in Nginx. This provides an additional layer of security for your web server and allows you to control access to protected resources.

nginx