HTTP Authentication using Nginx
I got a requirement from one of my clients to setup a staging server that has a HTTP authentication, behind an ELB. but because of authentication it fails in the ELB health check. I did the following steps to configure it with HTTP authentication.
- Create a single PHP or HTML file and disable HTTP authentication for this file.
- In the configure health check section pass that file name in the Ping Path.
- ELB gets the response on configured Ping Path because authentication is disabled for this file.
Few more tricks that can be used to setup HTTP authentication using nginx.
Create a htpasswd file with username : myuser & password : mypassword
Create a htpasswd that contains username and encrypted password. To create that file we need to install php CLI tools or it can be created from some other tools too.
[shell]sudo apt-get install php5-cli
php -a
php > echo crypt(‘mypassword’, base64_encode(‘mypassword’));
bX6j7x3Ep6RnU
echo ‘myuser:bX6j7x3Ep6RnU’ >> /etc/nginx/htpasswd[/shell]
Basic password protection
Add below code into the Nginx site configuration file that will enable authentication on the complete site.
[shell]location / {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/htpasswd;
}[/shell]
Open-access for a single IP, password-protect for everyone else
This will allow you to disable password for a single IP and enable password for the others. This method is great during project development when you want to give access for a single IP.
satisfy any
allow *.*.*.* ;
deny all;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/htpasswd;
}[/shell]
Open access for multiple IPs, password-protect for everyone else
That will allow you to disable password protection for multiple IPs.
location / {
satisfy any;
allow *.*.*.* ;
allow *.*.*.* ;
deny all;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/htpasswd;
}[/shell]
Password protection for everything except a single file
In a case you want to disable password protection for a single file only. I have used this technique countless times.
location / {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/htpasswd;
location /sample/abc.html {
auth_basic off;
}
}[/shell]
Password protect a single file
This will allow access to a single file while password-protecting everything else
location / {
location /sample/abc.html {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/htpasswd;
}
}[/shell]
Password protect a folder
If you have a use case to protect multiple files in a folder, So instead of protect multiple files you can protect that complete folder directly.
[shell]
location / {
location /sample/ {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/htpasswd;
}
}[/shell]
great article
Wow, great article.Really thank you! Great.
Really appreciate you sharing this article.Much thanks again. Much obliged.
Enjoyed every bit of your blog.Really thank you! Fantastic.