How To Set Up Password Authentication with Nginx

Vipul Munot
2 min readJun 5, 2019

--

I had a recent requirement to add an additional login screen on our development application for a client demo. This was to ensure that only authorized users can see our application under progress.

Things required?

  • nginx docker image
  • apache2-utils

Create the Password File Using Apache Utilities

$ sudo apt-get update
$ sudo apt-get install apache2-utils

The first time we use this utility, we need to add the -c option to create the specified file. We need to add the -b option to run batch mode; i.e., get the password from the command line rather than prompting for it. We specify a username (john in this example) at the end of the command and password (passwordin this example) to create a new entry within the file:

htpasswd -c -b /etc/nginx/.htpasswd  john password

Note: If you use -b option the password is clearly visible on the command line

Nginx Configuration Tweak

We have to change the nginx configuration for using the auth_basic directive to turn on authentication and to choose a realm name to be displayed to the user when prompting for credentials. We will use the auth_basic_user_file directive to point Nginx to the password file we created:

location / {
try_files $uri $uri/ =404;
auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;

}

Example Dockerfile Code

FROM nginx:latest
RUN apt-get update && \
apt-get dist-upgrade -y && \
apt-get install --no-install-recommends -y apache2-utils && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

RUN htpasswd -c -b /etc/nginx/.htpasswd john password

COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD /bin/sh -c /usr/sbin/nginx -g "daemon off;"

Example Nginx Configuration (default.conf)

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 "Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;
}
}

Confirm the Password Authentication

To confirm that your content is protected, try to access your restricted content in a web browser. You should be presented with a username and password prompt that looks like this:

Website Page

Conclusion

This is a simple way to add one more layer of authentication to your development application and you can give updates or demos to your client’s without creating a new environment just for updates!

--

--

Responses (1)