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      6,315    1

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 {
    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.

// 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.


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 :



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



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



When fixing a bug

By sonic0002