Using htpasswd to protect your website in Nginx

  sonic0002        2013-06-07 21:35:27       11,769        2    

We need to build a password protected website frequently such as an internal website within the team, demo website. Here what we are talking about is password protection in Nginx server level instead of application level registration and login. We are going to use Nginx server configuration and htpasswd file to achieve password authentication.

The final result looks like below(Different browsers may have different interfaces):

Authentication Required

If the authentication fails, it will report a HTTP error: 401 Authorization Required.

To achieve this function, we need to modify server configuration and create the username and password for login.

First we need to modify Nginx's server configuration, this file is usually located at /etc/nginx/sites-enabled/ in Ubuntu. We assume the file is /etc/nginx/sites-enabled/default.

server {
    server_name www.fancycedar.info
    root /www/fancycedar
 
    # ...
 
    location / {
        # Add below two lines
        auth_basic      "Restricted";
        auth_basic_user_file  htpasswd;
        # ...
    }
 
    # ...
}

Next creating htpasswd, here are something to be noted:

htpasswd path

It can be put in the same level of directories as nginx.conf. It can be in /etc/nginx/ in Ubuntu.

htpasswd content

Each line stores one user, format is username:password. Here password cannot be plain text, it should be encrypted using crypt(3). You can use some PHP codes to generate the password of htpasswd.

<?php
// Password plaintext
$password = 'some password';
// Encrypt password
$password = crypt($password, base64_encode($password));
// The password encrypted
echo $password;
?>

Then save the password string to htpasswd.

username1:xucqMk13TfooE
username2:YXTfb3xWKOMBM
...

htpasswd permission

If need to change the permission of htpasswd, run below commands:

sudo chown root:www-data htpasswd
sudo chmod 640 htpasswd

Are you ready?

After above steps are done, we can proceed with loading and restarting Nginx server.

sudo /etc/init.d/nginx reload
# or
sudo /etc/init.d/nginx restart

Source : http://www.fancycedar.info/2013/06/apache-nginx-htpasswd/

NGINX  PASSWORD PROTECTED  HTPASSWD 

       

  RELATED


  2 COMMENTS


Anonymous [Reply]@ 2017-09-18 07:01:58

Nice. 

Grabans.com

Mirko Tebaldi [Reply]@ 2021-08-24 08:13:38

How to protect all /* but not /api/* ?



  RANDOM FUN

Feel much better now