The final effect is similar (the interfaces of different browsers are different):
If the authentication fails, an http error will be reported: 401 authorization required.
To implement such a function, you need to change the server configuration and set the user name and password for login.
First we need to change the nginx server configuration of the website. For ubuntu server, this configuration file is usually located at /etc/nginx/sites-enabled/. For example, I use the default configuration file /etc/nginx/sites-enabled/ here. Default is an example:
Copy the code The code is as follows:
server {
server_name www.fancycedar.info
root /www/fancycedar
# ...
location / {
# Add the following two lines
auth_basic "restricted";
auth_basic_user_file htpasswd;
# ...
}
# ...
}
Next, you need to create the htpasswd file. Here are some details to pay attention to:
The path of htpasswd
is at the same level as nginx.conf Directory is enough. For Ubuntu servers, it is usually under /etc/nginx/.
The content of htpasswd
Each line is for one user, and the format is username:password. But please note that the password here is not plain text, but a string that is encrypted by crypt(3).
You can use a piece of php code to generate the password in htpasswd:
Copy the code The code is as follows:
//Password plain text
$password = 'some password' ;
// Encrypt the password
$password = crypt($password, base64_encode($password));
// Obtain the encrypted password
echo $password;
Then write the string into the htpasswd file:
Copy the code The code is as follows:
username1:xucqmk13tfooe
username2:yxtfb3xwkombm
...
htpasswd permissions
You need to change the permissions of the htpasswd file, execute the following command:
Copy the code The code is as follows:
sudo chown root:www-data htpasswd
sudo chmod 640 htpasswd
are you ready?
When the above preparations are done, we can reload or restart the nginx server:
Copy code The code is as follows:
sudo /etc/init.d/nginx reload
# or
sudo /etc/init.d/nginx restart
The above is the detailed content of How to use htpasswd to password protect the website in Nginx. For more information, please follow other related articles on the PHP Chinese website!