Restricting Access with HTTP Basic Authentication in Nginx

Restricting access to your website or some parts of it by implementing a username/password authentication.
Prerequisites
- Nginx
- Password file creation utility such as
apache2-utils
(Debian, Ubuntu) orhttpd-tools
(RHEL/CentOS/Oracle Linux).
Creating a Password File
1. The first time we use this utility, we need to add the -c
option to create the specified file. We specify a username (user1
in this example) at the end of the command to create a new entry within the file:
$ sudo htpasswd -c /etc/nginx/.htpasswd user1
Press Enter and type the password for user1 at the prompts.
2. (Optional) Create additional user-password pairs. Omit the -c
flag because the file already exists:
$ sudo htpasswd /etc/nginx/.htpasswd user2
3. (Optional) You can confirm that the file contains paired usernames and hashed passwords:
$ cat /etc/nginx/.htpasswd
user1:$apr1$/woC1jnP$KAh0SsVn5qeSMjTtn0E9Q0
user2:$apr1$QdR8fNLT$vbCEEzDj7LyqCMyNpSoBh/
user3:$apr1$Mr5A0e.U$0j39Hp5FfxRkneklXaMrr/
Configuring NGINX for HTTP Basic Authentication
Now that we have a file with our users and passwords in a format that Nginx can read, we need to configure Nginx to check this file before serving our protected content.
The default file should look similar to this:
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
root /usr/share/nginx/html;
index index.html index.htm;
server_name localhost;
location / {
try_files $uri $uri/ =404;
}
}
Specify the auth_basic_user_file directive with a path to the .htpasswd file that contain user/password pairs:
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
root /usr/share/nginx/html;
index index.html index.htm;
server_name localhost;
location / {
try_files $uri $uri/ =404;
auth_basic "Administrator’s Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
}
Save and close the file when you are finished. Restart Nginx to implement your password policy:
sudo service nginx restart
When you access your status page, you are prompted to log in:
If the provided name and password do not match the password file, you get the 401 (Authorization Required)
error:
Nginx's docs: https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/
DigitalOcean's toturial: https://www.digitalocean.com/community/tutorials/how-to-set-up-password-authentication-with-nginx-on-ubuntu-14-04