Some directories on the server may not be visible to everyone. The solution is to provide the user name and password for the users who need to access the server. If the authentication fails, an HTTP error 401 Authorization Required will be reported.
To implement this function, you need to change the server configuration and set the username and password for logon.
First, we need to change the Nginx server configuration of the website. We need to configure the following directories for authorized access:
Location /{
# Add the following two lines
Auth_basic "Restricted ";
Auth_basic_user_file htpasswd;
#...
}
Create an htpasswd file
Content of the htpasswd file
Each row is a user in the format of username: password. However, note that the password here is not in plain text, but the encrypted string of the password after crypt (3.
You can use a piece of PHP code to generate the password in htpasswd:
// Plaintext
$ Password = 'some password ';
// Encrypt the password
$ Password = crypt ($ password, base64_encode ($ password ));
// Obtain the encrypted password
Echo $ password;
Then write the string to the htpasswd file:
Username1: xucqMk13TfooE
Username2: YXTfb3xWKOMBM
...
Htpasswd permission
After the htpasswd file is created successfully, change the permissions of the htpasswd file and run the following command:
Sudo chown root: www-data htpasswd
Sudo chmod 640 htpasswd
After the above preparations are completed, we can re-load or restart the Nginx server:
Sudo/etc/init. d/nginx reload
# Or
Sudo/etc/init. d/nginx restart
For Alibaba Cloud users, use the following command:
Sudo chown root: www htpasswd
Sudo chmod 640 htpasswd
Restart nginx
Sudo/alidata/server/nginx/sbin/nginx-s reload