Secure Nginx Access with htpasswd Basic Authentication

nginx authenticationhtpasswdbasic authsecure phpmyadminnginx config
Published·Modified·

Nginx is a high-performance web server that is increasingly popular. If you have a site that you do not want to make public (such as phpMyAdmin), you can use htpasswd to implement Nginx access verification.

safey

Install htpasswd

htpasswd is an Apache password generation tool. Since Nginx supports auth_basic authentication, you can use the generated passwords in Nginx. Enter the following command to install:

yum -y install httpd-tools

The parameters are as follows:

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

Generate Password

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

If you do not want to install htpasswd, you can also use an online htpasswd generator to complete it.

Load Configuration

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

auth_basic "Please input password";   # The prompt message when verifying
auth_basic_user_file /home/passwd;

Troubleshooting

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

  • Change the permissions of the passwd file to match the Nginx user. For example, if your Nginx is configured to run as the www user: chown www:www /home/passwd
  • Do not place the file in directories like /root; try moving it to another public directory.

Access Test

When you visit the site again, you will be prompted to enter a username and password to access it. This method is suitable for sites that should not be public, such as phpMyAdmin, helping to avoid weak password scans and adding an extra layer of security.

2017-02-24_105459

This article references: Apache htpasswd command usage detailed explanation Nginx create website authentication access