How to use htpasswd to password protect the website in Nginx

王林
Release: 2023-05-17 15:49:06
forward
920 people have browsed it

The final effect is similar (the interfaces of different browsers are different):

How to use htpasswd to password protect the website in Nginx

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!