Today's Question:  What are you most afraid of as a programmer?        GIVE A SHOUT

Technical Article => Security =>  Data Security

Using htpasswd to protect your website in Nginx

  sonic0002      2013-06-07 21:35:27      5,304    0    0

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

  SAVE AS PDF   MARK AS READ   MARK AS IMPORTANT

Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious

  RELATED


  0 COMMENT


No comment for this article.


  WRITE ARTICLE

Bigger than bigger

By sonic0002
Bigger than bigger!!! -- iPhone 6/iPhone 6 plus. I am sure you will understand this