Implementing Nginx Access Authentication with htpasswd

Publish: 2017-02-24 | Modify: 2021-07-27

Nginx is a high-performance web server that is increasingly being used by more and more users. If you don't want to make a certain site public (such as PHPMyAdmin), you can use htpasswd to implement Nginx authentication.

safey

Installation of htpasswd

htpasswd is an Apache password generation tool. Nginx supports auth_basic authentication, so we can use the generated password for Nginx. Just enter one command to install: yum -y install httpd-tools, with the following parameters:

-c Create a passwdfile. If the passwdfile already exists, it will be overwritten and the original content will be deleted.
-n Do not update the passwordfile, just display the password directly.
-m Use MD5 encryption (default).
-d Use CRYPT encryption (default).
-p Use plain text format for the password.
-s Use SHA encryption.
-b Input the username and password in the command line instead of entering the password according to the prompt. The plaintext can be seen and no interaction is required.
-D Delete the specified user.

Generating Passwords

# Enter the home directory
cd /home
# Generate the password
htpasswd -c ./passwd username
# After executing the above command, you will be prompted to enter the password twice. ./passwd is the password file created in the current directory, and username is the account to be set.

If you don't want to install htpasswd, you can also use the Online htpasswd Generator to complete the process.

Loading Configuration

Next, add the following two lines to the Nginx configuration file (usually within the server block), and reload Nginx (service nginx reload) to take effect.

auth_basic "Please input password";   # This is the prompt information for authentication
auth_basic_user_file /home/passwd;

Troubleshooting

If you encounter a 500 error after enabling auth_basic authentication, please note:

  • Change the owner of passwd to the corresponding user in nginx, such as the www user configured in nginx: chown www:www /home/passwd
  • Do not put it in a directory like /root, please try moving it to another public directory

Access Testing

When accessing the site again, you will be prompted to enter a username and password to access. This method is suitable for sites that should not be public, such as PHPMyAdmin, which can avoid being scanned for weak passwords and adds an extra layer of security.

2017-02-24_105459

This article references:


Comments