I was working on a new customers website, and I was looking for ways to showcase current development stage to the client, meanwhile hiding contents from others. Sounds familiar? In this server series guide I will provide info how to set up basic HTTP authentication with Nginx on Ubuntu 14.04.
Most details for this article are taken from Digital Ocean's guide: How To Set Up Basic HTTP Authentication With Nginx on Ubuntu 14.04 with few minor adjustments.
As I'm serving more than just one domain from this development server, I had to take an extra step and configure following domain to be default on this machine, as I will provide just the IP address to customer. For setting up default domain on Nginx, see this article: How To Setup Ngnix Default Domain For Not Configured Domains or IP Address
Step 1 — Installing Apache Tools
You'll need the htpassword command to configure the password that will restrict access to the target website. This command is part of the apache2-utils package, so the first step is to install that package.
sudo apt-get install apache2-utils
Step 2 — Setting Up HTTP Basic Authentication Credentials
sudo htpasswd -c /opt/etc/nginx/.htpasswd USERNAME
be sure to check out the correct path for your ngnix config, and in place of USERNAME enter your desired one. You'll need to authenticate, then specify and confirm a password.
Step 3 — Updating the Nginx Configuration
Now that you've created the HTTP basic authentication credential, the next step is to update the Nginx configuration for the target website to use it.
sudo nano /etc/nginx/sites-available/reinisfischer.com
be sure to replace reinisficher.com with your domain name
Under the location section, add following directives:
auth_basic "Private Property"; auth_basic_user_file /opt/etc/nginx/.htpasswd;
Save and close the file.
Step 4 — Testing the Setup
To apply the changes, first reload Nginx.
sudo service nginx reload
Now try accessing the website you just secured by going to http://your_server_ip/ in your favorite browser. You should be prompted with a following screen:
Nginx authentication screen
Congrats, you have just set up a basic HTTP authentication with Ngnix on Ubuntu 14.40.