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):
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/
Nice.
Grabans.com