Nginx uses htpasswd to configure password protection for the website

Source: Internet
Author: User
Tags chmod crypt php code nginx server password protection


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.